Lukas G.
Lukas G.

Reputation: 28

Problem implementing interfaces into a class

I defined two interfaces outside a class. Then I implemented the two interfaces and tried to set them to private properties of the class but there is still something wrong but I can't imagine what.

Could anybody help me with that?

enter image description here

There are no error messages out of the compiler, but VSCode reveals:

enter image description here

Upvotes: 0

Views: 56

Answers (3)

Mayank Singh Fartiyal
Mayank Singh Fartiyal

Reputation: 957

You have implemented 2 interfaces on Handler but have not created interface properties in your class. If you need to make a field optional you can do it like so. (just put a question mark after the key.)

interface Isize {
  width? : number;
  height? : number;
}

In below case you will not get an error.

class Handler implements Isize, Iposition {
  public x; 
  public y;
  public height;
  public width:;
  .......
  ........
  .........
}

Upvotes: 0

Kamil Naja
Kamil Naja

Reputation: 6682

So, if you do not want change your class implementation, and you can change interfaces, you can use this:


interface Isize {
  size: {
    width: number;
    height: number;
  };
}

interface Iposition {
  position: {
    x: number;
    y: number;
  }
}

class Handler implements Isize, Iposition {
  position: { x: number; y: number; };
  size: { width: number; height: number; };
}

Upvotes: 1

nsevens
nsevens

Reputation: 2835

As the error message states: you need to implement the properties from the interfaces directly in the class. In this case this means:

class Handler implements Isize, Iposition {
  public width: number;
  public height: number;
  public x: number;
  public y: number

  constructor(x, y) {
    this.width = 300;
    this.height = 450;

    this.x = x;
    this.y = y;
  }
}

Upvotes: 2

Related Questions