Home > Back-end >  How to declare type according to the enum using Javascript?
How to declare type according to the enum using Javascript?

Time:07-19

I have an enum and I want to declare the type according to that enum. For example,

enum Animals {
  CAT = 'cat',
  DOG = 'dog',
}

And from that Animal I want to declare type like this

type MyType = {
  cat_price: string,
  cat_from: string,
  cat_color: string,
  dog_price: string,
  dog_from: string,
  dog_color: string,
}

So if I modify the Animal enum, the MyType will be modified automatically. How can I do this? Any comment will be helpful.

CodePudding user response:

Amazingly, this is actually possible in TypeScript thanks to template literal types and key remapping:

enum Animals {
  CAT = 'cat',
  DOG = 'dog',
}

type AnimalData = {
  price: number,
  from: string,
  color: string,
}

type MyType = {
  [Key in keyof AnimalData as `${Animals}_${Key}`]: AnimalData[Key]
}

const foo: MyType = {
  cat_price: 42,
  cat_from: 'Africa',
  cat_color: 'teal',
  dog_price: '37',  // Error! Type 'string' is not assignable to type 'number'.
  dog_from: 'Mexico',
  dog_colr: 'blue', // Error! Object literal may only specify known
                    // properties, but 'dog_colr' does not exist in type
                    // 'MyType'. Did you mean to write 'dog_color'?
}

Playground link

  • Related