Typescript 实现具有相同键但不同类型的接口

mat*_*ias 6 typescript

我有一个界面

export interface Foo {
 a: string;
 b: string;
}
Run Code Online (Sandbox Code Playgroud)

我现在想要另一个类,它实现接口的所有键,但可以有另一种类型:

  export class Bar implements keysof(Foo) {
    a: SomeNewType;
    b: SomeNewType2;
  }
Run Code Online (Sandbox Code Playgroud)

这在打字稿中可能吗?背景:我希望Bar班级的按键与Foo

Mei*_*hes 8

您可以使用键映射来完成此操作。

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

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

export class Bar implements HasKeys<Foo> {

}
Run Code Online (Sandbox Code Playgroud)

这会抱怨Bar缺少ab但如果你用任何类型定义它们,那就没问题了。IE

export class Bar implements HasKeys<Foo> {
  a: number;
  b: object;
}
Run Code Online (Sandbox Code Playgroud)