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)
As it turns out your code will work by making these 3 changes:
as const
after you array literal so thatclaims
is inferred as a (read-only) tupletypeof
operator withclaims[number]
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: