Reputation: 21
I've attempted to add a method onto my class but it is being recognized as a property rather than a method??
export class Shape {
color: string;
size: string;
constructor() {
this.color = 'Green';
}
getColor() {
return this.color;
}
}
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}'.
Upvotes: 2
Views: 277
Reputation: 321
As @tony19 said, getColor
isn't optional - it's a property on Shape
that the compiler is expecting when it casts each of the objects in the Shape[]
to Shape
. An alternative to using Partial<T>
might be to make color
and shape
members of the Shape
class that are set when a Shape
instance is instantiated:
class Shape {
constructor(private color: string, private size: string) {
this.color = color;
this.size = size;
}
getColor() {
return this.color;
}
getSize() {
return this.size;
}
}
const shapeList: Shape[]= [
new Shape('Red', 'Large'),
new Shape('Orange', 'Medium'),
new Shape('White', 'Small'),
]
for (const shape of shapeList) {
console.log(shape);
}
Upvotes: 2
Reputation: 1299
Use static getColor(), but you don't really need it as you can directly acces your object values.
In general we use a static method to parse or adapt an object to your class
Upvotes: -1
Reputation: 138546
getColor
is not optional, so it would be required in each Shape
array element. You could declare an array of partial Shape
s (a generic class with optional properties of T
) with Partial<Shape>
:
const shapeList: Partial<Shape>[]= [
{color: 'Red', size: 'Large'},
{color: 'Orange', size: 'Medium'},
{color: 'White', size: 'Small'}
];
Upvotes: 2