Typescript &引用;请考虑使用映射对象类型。什么';这是一种映射对象类型,在这里如何使用它?
我收到一条错误消息,如Typescript &引用;请考虑使用映射对象类型。什么';这是一种映射对象类型,在这里如何使用它?,typescript,Typescript,我收到一条错误消息,如 interface Foo { [foo: "hello" | "world"]: string; } 什么是映射对象类型,如何使用它?映射对象类型对一组单例类型进行操作,并生成一个新的对象类型,其中每个单例都转换为属性名称 例如,这: An index signature parameter type cannot be a union type. Consider using a mapped object type instead. 相当于 type
interface Foo {
[foo: "hello" | "world"]: string;
}
什么是映射对象类型,如何使用它?映射对象类型对一组单例类型进行操作,并生成一个新的对象类型,其中每个单例都转换为属性名称 例如,这:
An index signature parameter type cannot be a union type. Consider using a mapped object type instead.
相当于
type Foo = {
[K in "hello" | "world"]: string
};
请记住,映射的对象类型是一个独特的类型运算符-大括号中的语法不能用于接口或具有其他成员的对象类型。比如说
type Foo = {
"hello": string;
"world": string;
};
产生以下错误:
interface Foo {
[K in "hello" | "world"]: string
}
映射对象类型对于许多不同的事情都很有用。阅读这里的更多内容:是否有这样一个版本,类型只能有一个属性,其名称必须是
hello
或world
?这也是我试图弄明白的:如何创建一个类型,使其具有hello
或world
属性,并能够缩小键入范围以使用正确的类型…我想知道指出区别。要生成映射类型,我们将“:”替换为“in”。并成为[foo in“hello”|“world”]
注意答案将界面更改为类型
-这是我的解决方案。@ironchicken,是的,您只需在关闭]
后添加?
,更多详细信息如下:
A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.