ThomasReggi
ThomasReggi

Reputation: 59355

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'

Upvotes: 2

Views: 1349

Answers (2)

Karol Majewski
Karol Majewski

Reputation: 25790

The only valid types that can be used for keys are strings, numbers, and symbols. TypeScript provides a built-in alias for such a union called PropertyKey.

The built-in Record type will accept only one of these. That's why your type constructor needs to have the same constraint as well.

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

Upvotes: 3

Aaron Beall
Aaron Beall

Reputation: 52143

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

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

Upvotes: 5

Related Questions