首页 > 解决方案 > 我可以基于枚举定义接口吗?

问题描述

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

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 };

我有一个包含使用这些确切键的吸气剂的类:

export class MyClass {

    get one() { ... implementation ...}
    get two() { ... implementation ...}
    get three() { ... implementation ...}
    get four() { ... implementation ...}
}

我想知道是否有办法创建一个接口,该接口在实现时会强制类具有这些 getter。

我试过了

interface IClass{
  [key in MyTypeEnum ] : Function
}

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

标签: typescript

解决方案


这些 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 { }

推荐阅读