如何在Typescript中将对象的键限制为数组的字符串?

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
}


您可以使用const断言(在打字稿3.4中添加)来保留数组项的文字类型:

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"]

如果您的validKeys是静态的,则可以为其创建一个类型。 然后从该类型中,可以设置对象键的类型。
您可以执行以下操作:

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.