1

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
  • can you share playground reproduction link? Commented Nov 18, 2020 at 18:47

1 Answer 1

4

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

How would I do this in an interface itself. If I try to add [key in typeof claims[number]]?: boolean inside an interface, I get a lot of errors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.