我有一个界面
export interface Foo {
a: string;
b: string;
}
我想要另一个类来实现接口的所有键,但采用其他类型:
export class Bar implements keysof(Foo) {
a: SomeNewType;
b: SomeNewType2;
}
这在打字稿中可能吗?
您可以使用按键映射来完成此操作。
export interface Foo {
a: string;
b: string;
}
type HasKeys<T> = {
[P in keyof T]: any;
}
export class Bar implements HasKeys<Foo> {
}
这会抱怨
Bar
缺少 a
和 b
但如果你用任何类型定义它们就可以了。即
export class Bar implements HasKeys<Foo> {
a: number;
b: object;
}