如何使用 typescript 编写此内容?
所以我有一个 Status 类型,它具有三个属性:name、actionName 和 style。我还有一个常量 statusTypes,它有两个 Status 类型的属性。
这就是我到目前为止所做的,但它不起作用。我收到此错误 [ts] Type '{ Active: any;无效:任何; }' 不可分配给类型 'Status[]'。对象字面量只能指定已知属性,并且类型“Status[]”中不存在“Active”
export interface Status {
name: string;
actionName: string;
style: string;
}
export const statusTypes: Status[] = {
Active : {
name: "Active",
actionName: "Deactivate",
style: "success"
},
Inactive : {
name: "Inactive",
actionName: "Activate",
style: "warning"
}
};
最佳答案
正如其他人所提到的,问题在于它是一个数组:
如果那是你想要的模式,你应该像这样实现它:
interface StatusTypes {
Active: Status;
Inactive: Status
}
export interface Status {
name: string;
actionName: string;
style: string;
}
export const statusTypes: StatusTypes = {
Active : {
name: "Active",
actionName: "Deactivate",
style: "success"
},
Inactive : {
name: "Inactive",
actionName: "Activate",
style: "warning"
}
};
在 TS Playground 查看
无论什么时候你想拥有带键的对象,正确的方法是创建接口(interface),每个接口(interface)应该有一个属性,这将是对象的键。
英语:
通过为对象分配接口(interface)StatusTypes
,您告诉它它是一个具有Active
和Inactive
键的对象,其形状符合Status
界面。如果您想向 const statusTypes
添加另一个键,您可以将其添加到 StatusTypes
接口(interface)。如果您不想指定一个键,请附加“?”在属性的末尾:
interface StatusTypes {
Active: Status;
Inactive: Status
// This won't be required.
optional?: Status
}
关于javascript - 如何使用 Typescript 正确设置这些类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49325935/