Typescript 我可以基于枚举定义接口吗?

Typescript 我可以基于枚举定义接口吗?,typescript,Typescript,我有一个用于创建类型的枚举: export enum MyTypeEnum { one = 'one', two = 'two', three = 'three', four = 'four' } export type MyTypeKeyFunctionValue = { [key in MyTypeEnum ]?: Function }; export type MyTypeKeyStringValue = { [key in MyTypeEnum ]?:

我有一个用于创建类型的枚举:

export enum MyTypeEnum {
    one = 'one',
    two = 'two',
    three = 'three',
    four = 'four'
}

export type MyTypeKeyFunctionValue = { [key in MyTypeEnum ]?: Function };
export type MyTypeKeyStringValue = { [key in MyTypeEnum ]?: string };
我有一个类,它包含使用这些精确键的getter:

export class MyClass {

    get one() { ... implementation ...}
    get two() { ... implementation ...}
    get three() { ... implementation ...}
    get four() { ... implementation ...}
}
我想知道是否有一种方法可以创建一个接口,该接口在实现时会强制类拥有这些getter

我试过了

interface IClass{
  [key in MyTypeEnum ] : Function
}

但它不起作用。这可能吗?

这些getter在类公共API中仅表示为属性,因此强制实现者拥有这些属性getter的接口相当于:

interface MyTypeKeyGetters = {
  readonly one: any;
  readonly two: any;
  readonly three: any;
  readonly four: any;
} 
您可以基于枚举构建这样的类型,并直接实现它:

export enum MyTypeEnum {
    one = 'one',
    two = 'two',
    three = 'three',
    four = 'four'
}

export type MyTypeKeyGetters = {
  readonly [key in MyTypeEnum]: any
};

export class MyClass implements MyTypeKeyGetters{

  get one() { return ""; }
  get two() { return ""; }
  get three() { return ""; }
  get four() { return ""; } // error if we omit one. 
}
注意无法保证使用getter实现字段,实现类也可以使用字段

虽然它实际上不是一个接口,但它可以作为一个接口来实现。接口中不直接支持映射类型语法。如果希望使用接口而不是类型别名,可以定义扩展映射类型的接口:

type MyTypeKeyGetters = {
  readonly [key in MyTypeEnum]: any
};
export interface MyTypeKeyGettersInterface extends MyTypeKeyGetters { }

多好的解释啊!谢谢@titian cernicova dragomir。创建一个空接口会触发
ts lint
警告无空接口,当我在实现中将鼠标悬停在接口上时,我不会获得有关接口结构的信息(在vscode中)。所以我将使用类型定义。