I d like to type an array so that the only allowed values in the array are the values of a certain key in a list of objects.
从原则上讲,我知道可以这样做:
const page1 = {
videoTitles: [ someTitle , otherTitle ],
} as const
const page2 = {
videoTitles: [ title , goodTitle ],
} as const
const allVideos = [...page1.videoTitles, ...page2.videoTitles]
// As desired, the if statement raises an error because badTitle isn t in either of the lists
if (allVideos.includes( badTitle )) {
console.log( Found! )
}
然而,我喜欢做的是给物体以某种类型,并引起同样的行为,但我只能说明如何这样做。 这里我大致喜欢:
type PageWithVideos = { readonly videoTitles: readonly string[] }
const page1: PageWithVideos = {
videoTitles: [ someTitle , otherTitle ],
} as const
const page2: PageWithVideos = {
videoTitles: [ title , goodTitle ],
} as const
const allTitles = [...page1.videoTitles, ...page2.videoTitles]
// Now, however, I don t get the same error. allTitles is just a string[]
if (allTitles .includes( badTitle )) {
console.log( Found! )
}
I ve found that I can really force it with something like this:
type PageWithVideos<T extends string> = { readonly videoTitles: readonly T[] }
const page1: PageWithVideos< someTitle | otherTitle > = {
videoTitles: [ someTitle , otherTitle ],
} as const
const page2: PageWithVideos< title | goodTitle > = {
videoTitles: [ title , goodTitle ],
} as const
const allVideos = [...page1.videoTitles, ...page2.videoTitles] as const
// I m getting the error again (which is good), but this is a little silly
if (allVideos.includes( badTitle )) {
console.log( Found! )
}
但我更希望不要重复名单上的每一个标题和通用名称。 任何想法都会受到赞赏!