Home > OS >  I have an interface with 200 properties. How can a class implement this interface without declaring
I have an interface with 200 properties. How can a class implement this interface without declaring

Time:12-06

I have an interface with 200 properties and a class that uses these same properties.

interface MyProperties {
  property1: string
  property2: string
  ...
  property232: string
}

class MyClass {
  constructor() {
    this.property1 = 'foo';
    this.property2 = 'bar';
    ...
    this.property232 = 'bar';
  }
}

Right now typescript will give me this error: Property 'property1' does not exist on type 'MyClass'.

Is there a way to tell typescript that my class properties come from the MyProperties interface?

I dont want to do something like this:

class MyClass {
  property1: string
  property2: string
  
  constructor() {
    this.property1 = 'foo';
    this.property2 = 'bar';
  }
}

since the interface is already used extensively in my code and I don't want to repeat these typings.

Closest I've come is this

class MyClass {
  property1: MyProperties['property1'];
  property2: MyProperties['property2'];
  ...
  property232: MyProperties['property232'];

  constructor() {
    this.property1 = 'foo';
    this.property2 = 'bar';
    ...
    this.property232 = 'bar';
  }
}

but it's not super pretty, since in my actual code I have 200 properties

CodePudding user response:

Well just add an implements MyProperties clause to the class:

interface MyProperties {
    property1: string
    property2: string
}

class MyClass implements MyProperties {
    property1: string;
    property2: string;

    constructor() {
        this.property1 = 'foo';
        this.property2 = 'bar';
    }
}

CodePudding user response:

Right now typescript will give me this error

Thats because there are no definition in class for this properties. You should tell TypeScript compiler that MyClass has this properties:

class MyClass {
    property1: string;
    property2: string;
    constructor() {
        this.property1 = 'foo';
        this.property2 = 'bar';
    }
}

Now, compiler know what properties MyClass has and can realize that MyClass implementing MyProperties interface:

interface MyProperties {
    property1: string
    property2: string
}

class MyClass {
    property1: string;
    property2: string;
    constructor() {
        this.property1 = 'foo';
        this.property2 = 'bar';
    }
}

const a: MyProperties = new MyClass(); // no error here

Also you can explicitly implement MyProperties interface to improve readability of code using implements MyProperties:

interface MyProperties {
    property1: string
    property2: string
}

class MyClass implements MyProperties {
    property1: string;
    property2: string;
    constructor() {
        this.property1 = 'foo';
        this.property2 = 'bar';
    }
}

const a: MyProperties = new MyClass(); // no error here too
  • Related