tomwolber
tomwolber

Reputation: 516

Is there a better way to have a class use an interface in Typescript?

I have an interface with 13 properties. Do I really have to repeat them 3 times in the class? This is the only way I can make the compiler happy.

export interface SimpleInterface {
  foo: number;
  bar: number;
  baz: number;
  bam: number;
  ...
}

export class SimpleClass implements SimpleInterface {
  foo: number;
  bar: number;
  baz: number;
  bam: number;
  ...

  constructor(inputs: SimpleInterface) {
      this.foo = inputs.foo;
      this.bar = inputs.bar;
      this.baz = inputs.baz;
      this.bam = inputs.baz;
     ...
  }
  
}

Upvotes: 1

Views: 32

Answers (1)

You can do a small refactor:

export interface SimpleInterface {
  foo: number;
  bar: number;
  baz: number;
  bam: number;
}

interface Options {
  options: SimpleInterface
}

export class SimpleClass implements Options {
  // the magic is in `public` keyword
  constructor(public options: SimpleInterface) {
      this.options = options
  }  
}

Just pack all properties into one options.

Please find more here

Upvotes: 1

Related Questions