I have an interface like this
interface Cat {
color: string,
weight: number,
cute: Boolean, // eventhough all cats are cute!
}
Now, I have to do something like this
const kitten: Cat = ...
Object.keys(kitten).some(prop => ['weight', 'color'].includes(prop)
Is there a way to make sure, that the strings passed to the array
(['weight', 'color']
) are part of the interface
Cat
?
CodePudding user response:
const arr: (keyof Cat)[] = ["weight", "color"]
Object.keys(kitten).some(prop => arr.includes(prop)
or for typescript 4.9 or higher
Object.keys(kitten).some(prop => (['weight', 'color'] satisfies (keyof Cat)[]).includes(prop))
to bypass Object.keys
error.
type ObjectKeys<T> = (keyof T)[];
(Object.keys(kitten) as ObjectKeys<Cat>).some(prop => (['weight', 'color'] satisfies (keyof Cat)[]).includes(prop))