Home > Software design >  Typescript interface array as class member
Typescript interface array as class member

Time:09-16

class member as interface array

what's wrong with my code i don't understand why this.circles.length is undefine

interface Point {
  x: number;
  y: number;
}
interface Circle {
  xy: Point;
  radius: number;
}

class Canvas {
  circles: Circle[]; //**interface Circle as Canvas member**
  constructor() {
    this.circles.push({
      xy: {
        x: 10,
        y: 10,
      },
      radius: 0,
    });

    console.log(this.circles.length); //error
  }
}

CodePudding user response:

It is because Typescript is just a type system, you still need to do JS stuff to make it work properly.

interface Point {
  x: number;
  y: number;
}

class Canvas {
  circles: Circle[] = []; // add an empty array here
  constructor() {
    console.log(this.circles.length); // it should work now
  }
}

Why?

Look by this example instead. Since Typescript is just a type system, all the types will be wiped out when you compile it to Javascript.

// typescript
let circle: Circle;

// compiled to javascript
let circle; // have no value (undefined)

And so is the array.

// typescript
let circles: Circle[];

// compiled to javascript
let circles; // have no value (undefined)

That's why you can't .push() or .length because it is undefined.

CodePudding user response:

You need to create/ initialize the array first. You can initialize it with one element already in the array like this:

interface Point {
  x: number;
  y: number;
}

interface Circle {
  xy: Point;
  radius: number;
}

class Canvas {
  circles: Circle[]; //**interface Circle as Canvas member**

  constructor() {
    this.circles = [{ // create and initialize array with one member
      xy: {
        x: 10,
        y: 10,
      },
      radius: 0,
    }];

    console.log(this.circles.length); // prints "1"
  }
}

new Canvas()

Expected output:

1

An equivalent implementation of the constructor() doing the above in two steps would look like this:

constructor(){
    this.circles = [];
    this.circles.push({
      xy: {
        x: 10,
        y: 10,
      },
      radius: 0,
    });
    console.log(this.circles.length);
}
  • Related