Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Key / Value type from enum and interface

Tags:

typescript

I am looking for a custom type that would allow me to create an object with keys from a enum and that all match the value from a specific interface. Is there an easy way to create the Custom type below?

enum MyKeys {
  ALPHA = 'ALPHA',
  BETA = 'BETA',
  GAMMA = 'GAMMA',
}

interface MyValues {
  in: any[];
  out: any[];
}

type Example = Custom<MyKeys, MyValues>

Should be valid against:

{
  [MyKeys.ALPHA]: {
    in: []
    out: []
  },
  [MyKeys.BETA]: {
    in: []
    out: []
  },
  [MyKeys.GAMMA]: {
    in: []
    out: []
  }
}
like image 597
ThomasReggi Avatar asked Sep 04 '26 08:09

ThomasReggi


1 Answers

You're just looking for the Record<K, V> type from the standard library. It's a mapped type where the value types don't depend on the keys. The ability to use string-based enums as key types in TypeScript was added in TypeScript 2.6.

Let's see it in action:

type Example = Record<MyKeys, MyValues>
const ex: Example = {
  [MyKeys.ALPHA]: {
    in: [],
    out: []
  },
  [MyKeys.BETA]: {
    in: [],
    out: []
  },
  [MyKeys.GAMMA]: {
    in: [],
    out: []
  }
}; // works

Looks good. Hope that helps; good luck.

like image 158
jcalz Avatar answered Sep 07 '26 02:09

jcalz