我尝试创建具有可变值作为属性
的类型例如:
const myProp: string = 'my prop';
type Foo ={
[myProp]: string
};
我希望我能做:
const test: Foo = {
[myProp] = myProp
}
,但获取错误:
[ts]类型文字中计算的属性名称必须直接参考 内置符号。
如果要声明具有与字符串常数相同属性名称的类型
const myProp = 'my prop';
type Foo = {
[P in typeof myProp]: string
};
const test: Foo = {
[myProp]: myProp
}
如果您想拥有其中几个键,则可以使用联合类型:
const myProp = 'my prop';
const otherProp = "otherProp"
type Foo = {
[P in (typeof myProp | typeof otherProp)]: string
};
const test: Foo = {
[myProp]: myProp,
[otherProp]: otherProp
}
打字稿默认库,实际上提供了一种等同于上述查找类型声明的类型,名为Record
。您可以将您的类型写为:
type Foo2 = Record<typeof myProp, string>;
您将能够在发布的下一个版本的打字稿中执行此操作。
此功能在TypeScript@Next中已经可用。如果需要,可以安装它:
npm install typescript@next --save-dev
同时,您可以使用@titian Cernicova-Dragomir提供的方法