javascript - How to make Typescript enum with implements interfaces - Stack Overflow

How to make Typescript enum with implements interfacesi current has this 2 enumall enum ENNAME keys sho

How to make Typescript enum with implements interfaces

i current has this 2 enum

all enum ENNAME keys should only include of enum POSTAG keys

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',
}

is there has any way make something like this??

export interface ENNAME
{
    [k: keyof POSTAG]: string,
}

How to make Typescript enum with implements interfaces

i current has this 2 enum

all enum ENNAME keys should only include of enum POSTAG keys

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',
}

is there has any way make something like this??

export interface ENNAME
{
    [k: keyof POSTAG]: string,
}
Share Improve this question asked Jan 8, 2019 at 18:59 blueloversbluelovers 1,2652 gold badges12 silver badges25 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You can't make an enum extend an interface. The best you can do is set up some pile-time checking of the types to produce a warning if you make a mistake, such as:

interface ENNAMEInterface extends Record<Exclude<keyof typeof POSTAG, "BAD">, string> { }
type VerifyExtends<T, U extends T> = true
type VerifyENNAME = VerifyExtends<ENNAMEInterface, typeof ENNAME>; // okay

That should pile if the value ENNAME has the same keys as the value POSTAG (minus "BAD") with string values. Otherwise, VerifyENNAME will give you an error:

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'.

Hope that helps. Good luck!

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745353704a4623993.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信