How to limit the keys of an object to the strings of an array in Typescript?
假设我有一个有效的键名数组
1 | const validKeys = ['a', 'b', 'c'] |
如何创建仅接受这些键的对象类型? 这不起作用:
1 2 3 | interface MyObject { [key in validKeys]: number // for example } |
您可以使用
1 2 3 4 5 | const validKeys = ['a', 'b', 'c'] as const; type Keys = (typeof validKeys)[number]; //"a" |"b" |"c" type MyObject = { [key in Keys]: number } // { a: number; b: number; c: number; } |
操场
如果您使用较旧的打字稿版本(> = 3.0),则可以添加小型实用程序函数,该函数会将参数转换为文字的元组:
1 2 | const tuple = <T extends string[]>(...args: T): T => args; const validKeys = tuple('a', 'b', 'c'); // ["a","b","c"] |
如果您的
您可以执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 | type ValidKeys = 'a' | 'b' | 'c' type MyObject = { [key in ValidKeys]?: number //You can remove ? if all the keys are mandatory } const validKeys: ValidKeys[] = ['a', 'b', 'c'] const obj: MyObject = { a: 1, b: 1, c: 1 } |
The keys of object
obj can only be one of ValidKeys.