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 ]?: string };
我有一个包含使用这些确切键的吸气剂的类:
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 { }
推荐阅读
- jenkins - 访问 Jenkins 中的魅力报告统计信息(使用 Webdriverio 进行测试)
- automata - DFA 中的最小状态数
- python - 在不使用 Python 库的情况下计算矢量梯度
- python - 在 Python 中的数据框中添加排名列
- java - java.awt.Toolkit.getDefaultToolkit().createImage(byte[]) 返回 Null
- spring - 当分页大小超过预期时,Spring Boot v2.2.2.RELEASE 抛出错误
- c - 指向链表开头的指针
- java - Sublime text 3编译后在cmd上显示Java程序输出
- python - 运行 setup.py 或 pysetup.bat 后无法“导入 gurobipy”
- c# - 使用包含双引号的字符串(无需手动转义)的任何方式