[英]Typescript how to type custom key in an object
I have a function like this:我有一个这样的功能:
interface IUseTest { settings: { id: string } }; const useTest = (properties: IUseTest) => { const { settings } = properties; const test = ( item: { [settings.id]: string | number, // Error here [key: string]: any } ): object => { // function logic, doesn't matter }; return { test }; };
I should set an item with required key which I get from the settings object, but I got the error:我应该使用从设置对象中获得的必需键来设置一个项目,但出现错误:
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.
类型文字中的计算属性名称必须引用类型为文字类型或“唯一符号”类型的表达式。
what I have to do?我该怎么办?
UPDATE: is there a way to not use an interface?更新:有没有办法不使用接口?
UPDATE: the item can be like this: { id: 'someId' }
or { key: 'someKey' }
更新:项目可以是这样的:
{ id: 'someId' }
或{ key: 'someKey' }
UPDATE: typescript's version is 4.0.3
更新:打字稿的版本是
4.0.3
You can use Generics and Mapped Types , like so:您可以使用泛型和映射类型,如下所示:
interface IUseTest<T extends string> {
settings: {
id: T
}
};
const useTest = <T extends string>(properties: IUseTest<T>) => {
const { settings } = properties;
const test = (
item: { [settingsId in T]: string | number } & {
[key: string]: any
}
): object => {
// function logic, doesn't matter
};
return {
test
};
};
Here, <T>
is the generic and { [settingsId in T]: string | number }
这里,
<T>
是泛型和{ [settingsId in T]: string | number }
{ [settingsId in T]: string | number }
is the Mapped Type. { [settingsId in T]: string | number }
是映射类型。
Is this what you want?这是你想要的吗?
const settings = {
id: 'id',
};
type Settings = typeof settings;
interface Item extends Settings {
[key: string]: any;
}
const test: (item: Item) => object = (item) => {
return {};
// function logic, doesn't matter
};
You could try const assertion .你可以试试const assertion 。
const settings = {
id: 'id'
} as const;
That should fix your error.那应该可以解决您的错误。 If you're running a typescript version lower than 3.4 then typecast your
id
property in settings
.如果您运行的是低于 3.4 的打字稿版本,则在
settings
您的id
属性进行类型转换。
const settings = {
id: 'id' as 'id'
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.