0

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

2
  • 3
    Please do not publish code images, much better is paste code into code block! Commented Aug 2, 2019 at 19:26
  • Haha I'm sorry but I thought it looks way better ;) Next time I'm going to use the code block feature ;) Commented Aug 2, 2019 at 19:32

3 Answers 3

2

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;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh ok. But how can I access the properties later on. I mean if they are properties each it doesn't make a difference to implement them via interfaces, does it? I try to code as clean as possible and like to use typed based objects... Thank you very much :)
Sure it does, to access the object later on you could have let position: Iposition = new Handler(10, 20); where you can get the properties with position.x and position.y. The object doesn't care that it also implements Iposition, but still is sure to have all the required x and y information.
1

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

Comments

0

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:;
  .......
  ........
  .........
}

1 Comment

Thank you very much! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.