angular - 在 Typescript 中将项目添加到接口数组列表
问题描述
我有一个名为 SelectItem 的接口,由 primeNG 自动创建,如下所示。我想创建一个实例并添加我的选择项数组。如果 SelectItem 是类而不是接口,则代码将起作用。但是现在,给出一个错误。请不要建议将 SelectItem 的类型从 interface 更改为 "class"。我无法更改,因为它是 primeNG 的组成部分。我怎样才能做到这一点?
选择项.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
TypeScript 的核心原则之一是类型检查关注值的形状。这有时被称为“鸭子类型”或“结构子类型”。在 TypeScript 中,接口扮演命名这些类型的角色,并且是在代码中定义合约以及与项目外部代码的合约的强大方式。
因此,任何满足该合同的对象都可以被视为SelectItem
. 创建一个实例并没有真正的意义,因为在运行时接口被完全剥离。它们只是为了“开发时间”的方便。
推荐阅读
- r - 使用 specaccum() 外推物种累积曲线
- python - python函数标记数据帧中前30%的事务
- r - 具有 2 个捕获组的正则表达式,“key=value”或“value_only”
- java - 当读取和写入请求来自同一段时,ConcurrentHashMap 如何工作?
- wordpress - 在 WooCommerce 中为每个购物车项目设置运输方式
- typescript - 如何在我的 http 服务器中使用 Express Session?
- flutter - 广告未在颤动中显示时占用的空白空间
- python - Python子进程导出环境变量(使用其他环境变量)
- android - 颤振“字符串”不是“列表”类型的子类型
' - javascript - 如何等待功能完成?