如何使用实现接口制作Typescript枚举
我当前有2个枚举
所有enum ENNAME
键应只包含enum POSTAG
键
export enum POSTAG
{
BAD = 0x80000000,
D_A = 0x40000000,
D_B = 0x20000000,
D_C = 0x10000000,
}
export enum ENNAME
{
D_A = 'a',
D_B = 'b',
D_C = 'c',
}
有什么办法做这样的事情吗?
export interface ENNAME
{
[k: keyof POSTAG]: string,
}
答案 0 :(得分:2)
您不能使enum
扩展interface
。最好的办法是对类型进行一些编译时检查,以免在输入错误时发出警告,例如:
interface ENNAMEInterface extends Record<Exclude<keyof typeof POSTAG, "BAD">, string> { }
type VerifyExtends<T, U extends T> = true
type VerifyENNAME = VerifyExtends<ENNAMEInterface, typeof ENNAME>; // okay
如果值ENNAME
与具有字符串值的值POSTAG
(减去"BAD"
)具有相同的键,则应该编译该代码。否则,VerifyENNAME
会给您一个错误:
export enum ENNAME {
D_A = 'a',
D_B = 'b',
// oops, D_C is missing
}
type VerifyENNAME = VerifyExtends<ENNAMEInterface, typeof ENNAME>; // error
// ~~~~~~~~~~~~~
// Property 'D_C' is missing in type 'typeof ENNAME' but required in type 'ENNAMEInterface'.
希望有帮助。祝你好运!