Issue
I would like to do:
type PossibleKeys = 'a' | 'b' | 'c'
... and now I would like to create a type which the key has to be necessarily one of the above. Like:
type MyType = {
a: number;
b: string;
c: boolean;
d: {} // <--- I want it not to be allowed because `d` does not extend `PossibleKeys`
}
How would you do that?
Solution
You can create your own type validator:
type ValidateKeys<
K,
T extends ([keyof T] extends [K] ? [K] extends [keyof T] ? unknown : never : never)
> = T
type PossibleKeys = 'a' | 'b' | 'c'
type MyType = ValidateKeys<PossibleKeys, {
a: number;
b: string;
c: boolean;
}>
Answered By - tokland
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.