【问题标题】:Can I define an Interface based on an Enum?我可以基于枚举定义接口吗?
【发布时间】:2019-01-14 02:08:24
【问题描述】:

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

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
}

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

【问题讨论】:

    标签: typescript


    【解决方案1】:

    这些 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 警告 no-empty-interface 并且当我将鼠标悬停在实现中的接口上时,我没有获得有关接口结构的信息(这在 vscode 中)。所以我会使用类型定义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多