Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript implement interface with same keys but different types

Tags:

typescript

I have an interface

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

I want to have another class that implements all keys of the interface but in other types:

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

Is this possible in typescript?

like image 586
matthias Avatar asked Jun 21 '26 21:06

matthias


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;
}
like image 73
Meirion Hughes Avatar answered Jun 23 '26 12:06

Meirion Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!