我有一个名为 SelectItem 的界面,由 primeNG 自动创建,如下所示。我想创建一个实例并添加我的选择项数组。如果 SelectItem 是类而不是接口(interface),则代码将有效。但现在,报错了。 请勿建议将 SelectItem 的类型从接口(interface)更改为“类”。我无法更改,因为它是 primeNG 的组成部分。我怎样才能实现这个目标?
selectitem.ts
export interface SelectItem {
label?: string;
value: any;
styleClass?: string;
icon?: string;
title?: string;
disabled?: boolean;
}
我的方法
addUnselectedItem(selectItemList: SelectItem[]) {
let selectItem = new SelectItem(); //this row giving error
selectItem.value = "";
selectItem.label = "Please Select";
selectItemList.push(selectItem);
}
最佳答案
您可以简单地:
selectItemList.push({
value: "",
label: "Please Select",
});
https://www.typescriptlang.org/docs/handbook/interfaces.html
One of TypeScript’s core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”. In TypeScript, interfaces fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.
因此,任何满足该契约的对象都可以被视为SelectItem
。创建实例实际上没有意义,因为在运行时接口(interface)被完全剥离。它们只是为了“开发时间”的方便。
关于angular - 在 Typescript 中向界面数组列表添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52419773/