angular - 在 Typescript 中向界面数组列表添加项目

标签 angular typescript

我有一个名为 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/

相关文章:

angular - ngrx/store 未显示表单的更新值

javascript - 通过 .catch() 传播被拒绝的 promise

javascript - 取消 Angular 形式时撤消对模型状态的更改

javascript - 如何使用 TypeScript 和来自 github 的 Chartjs.definitelyTyped 来计算 Chartjs

javascript - 黑白 React Typescript、React JavaScript 和 React Native 的区别?

angular - 路由动画 Angular 4

Angular Material 垫波纹不起作用

http - 如何从 Observables 值构造数据,并在 HTTP 调用后返回 Observable<Response>?

html - Angular 2 - TypeError : Cannot read property 'apply' of undefined

javascript - 如何从 React/Typescript 应用程序中的选择选项获取附加数据