How do I use an array of strings to be an interface's keys?

348 Views Asked by At

Suppose I have this array of strings:

const claims = ['val1','val2','val3','val4', ...]

How can I build an interface based on the values in claims like this:

interface Claims {
  val1: boolean
  val2: boolean
  val3: boolean
  val4: boolean
  ...
}

I'm using Typescript 3.7.x


I tried playing off of this answer: https://stackoverflow.com/a/46344193/1439748

interface Claims{
 [key in claims[number]]?: boolean
}

But received these errors:

A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1169)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)
'number' only refers to a type, but is being used as a value here.ts(2693)
1

There are 1 best solutions below

1
On BEST ANSWER

As it turns out your code will work by making these 3 changes:

  • place as const after you array literal so that claims is inferred as a (read-only) tuple
  • use the (type space) typeof operator with claims[number]
  • instead of an interface use a type alias combined with a object type literal; as it turns out an interface does not work whereas a object type literal will.

I ended up with the following code:

const claims = ['val1','val2','val3','val4'] as const;

type Claims = {
  [key in typeof claims[number]]?: boolean
}