javascript - 类方法无法识别

标签 javascript angular typescript

我试图在我的类中添加一个方法,但它被识别为属性而不是方法?

形状.ts

export class Shape {
   color: string;
   size: string;

   constructor() {
     this.color = 'Green';
   }

   getColor() {
     return this.color;
   }
}

模拟数据.ts

import { Shape } from './shape.ts';

export const shapeList: Shape[]= [
  {color: 'Red', size: 'Large'},
  {color: 'Orange', size: 'Medium'},
  {color: 'White', size: 'Small'}
]

错误

ERROR in src/app/mock-data.ts(5,14): error TS2322: Type '{ color: string, size: string}' is not assignable to type 'Shape[]'.
  Type '{ color: string, size: string}' is not assignable to type 'Shape'.
    Property 'getColor' is missing in type '{ color: string, size: string}'.

最佳答案

getColor不是可选的,因此每个 Shape 中都需要它数组元素。您可以声明一个 partial 的数组Shape s (具有可选属性 T 的泛型类)和 Partial<Shape> :

const shapeList: Partial<Shape>[]= [
  {color: 'Red', size: 'Large'},
  {color: 'Orange', size: 'Medium'},
  {color: 'White', size: 'Small'}
];

demo

关于javascript - 类方法无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48132307/

相关文章:

javascript - ENOENT : no such file or directory preview. vue、prismic 模块和 nuxt-i18n

javascript - '+' 在 AngularJS 中执行连接而不是加法

javascript - 我如何模拟 HTML 密码字段(但会触发 keydown 事件)?

javascript - 在运行时创建下拉菜单并随后绑定(bind)下拉列表值 - ngOptions 不起作用

angular - 制作 ngb 可拖动模态

javascript - Angular 2 回调

angular - 在 2 个不同的系统上访问相同的 Angular 2 应用程序时,当我在 1 个系统上滚动时,它会自动在另一个系统上滚动相同的页面

javascript - 如何在 Angular 中制作异步函数?

angular - RangeError : Maximum call stack size exceeded when using valueChanges. 订阅

javascript - 从什么时候开始 null.toString() 返回 [object Null]?