首页 > 解决方案 > 在 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);
  }

标签: angulartypescript

解决方案


您可以简单地:

selectItemList.push({
  value: "",
  label: "Please Select",
});

https://www.typescriptlang.org/docs/handbook/interfaces.html

TypeScript 的核心原则之一是类型检查关注值的形状。这有时被称为“鸭子类型”或“结构子类型”。在 TypeScript 中,接口扮演命名这些类型的角色,并且是在代码中定义合约以及与项目外部代码的合约的强大方式。

因此,任何满足该合同的对象都可以被视为SelectItem. 创建一个实例并没有真正的意义,因为在运行时接口被完全剥离。它们只是为了“开发时间”的方便。


推荐阅读