ThomasReggi
ThomasReggi

Reputation: 59455

Custom Key / Value type from enum and interface

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: []
  }
}

Upvotes: 3

Views: 373

Answers (1)

jcalz
jcalz

Reputation: 329013

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.

Upvotes: 2

Related Questions