javascript - Klassmetod känns inte igen


Jag har försökt att lägga till en metod i min klass men den känns igen som en egenskap snarare än en metod??

shape.ts

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

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

   getColor() {
     return this.color;
   }
}

mock-data.ts

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

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

Fel

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}'.

Svar #1

getColor är inte valfri, så den skulle krävas i varje Shape-arrayelement. Du kan deklarera en array av partiella Shapes (en generisk klass med valfria egenskaper av T) med Partial<Shape>:

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

demo

Svar #2

Som @tony19 sade, getColor är inte valfritt - det är en egenskap på Shape som kompilatorn förväntar sig när den kastar varje objekt i Shape[] till Shape. Ett alternativ till att använda Partial<T> kan vara att göra color och shape till medlemmar av Shape-klassen som sätts när en Shape-instans skapas:

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);
}