Search code examples
typescriptgenericsenumstype-constraints

Creating a type that takes enum argument


I am trying to create a reusable type utilizing the Record type.

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

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

type Case<T> = Record<T, MyValues>;

Ideally I can use Case<MyKeys> instead of Record<MyKeys, MyValues>.

Type 'T' does not satisfy the constraint 'string | number | symbol'.

Type 'T' is not assignable to type 'symbol'


Solution

  • The type argument T needs to be constrained to a valid index type:

    type Case<T extends string> = Record<T, MyValues>;