How to make Typescript enum with implements interfaces

2

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,
}
javascript
node.js
typescript
types
enums
asked on Stack Overflow Jan 8, 2019 by bluelovers

1 Answer

3

You can't make an enum extend an interface. The best you can do is set up some compile-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 compile 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!

answered on Stack Overflow Jan 8, 2019 by jcalz • edited Dec 4, 2020 by jcalz

User contributions licensed under CC BY-SA 3.0