Typescript implement interface with same keys but different types

Viewed 1192

I have an interface

export interface Foo {
 a: string;
 b: string;
}

I want now to have another class which implements all keys of the interface but can have another type:

  export class Bar implements keysof(Foo) {
    a: SomeNewType;
    b: SomeNewType2;
  }

Is this possible in typescript? Background: I want the Bar class' keys to be in sync with Foo

1 Answers

You could potentially do it with a key map.

export interface Foo {
  a: string;
  b: string;
}

type HasKeys<T> = {
  [P in keyof T]: any;
}

export class Bar implements HasKeys<Foo> {

}

this will complain that Bar is missing a and b but it will be fine if you define them with any type. i.e.

export class Bar implements HasKeys<Foo> {
  a: number;
  b: object;
}
Related