我试图在我的类中添加一个方法,但它被识别为属性而不是方法?
形状.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'}
];
关于javascript - 类方法无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48132307/