0

I have an object with both keys and values as strings.
const obj: {[key: string]: string} = {first: 'a', second: 'b'}

I would like to declare that object values must be one of array values:
Example:

const arr: string = ['a', 'b', 'c']
const b: {[key: string]: string/*valueOf(arr)*/} = {
  first: 'a', // to be legal
  second: 'f', // to throw an error
}

Searched for a similar case, but in my case arr is an array instead of a type.

How can I declare that right?

Yinon
  • 945
  • 1
  • 8
  • 21
  • I think it should be possible because it's not possible to determine values of your array in the compile time. E.g. you can call `arr.push('d');` and it should change the type of your `b` variable. – Roman Koliada Jun 04 '19 at 10:07
  • 1
    If contents of the array can change at runtime, you cannot declare such typing, because the types are checked at compile time. If the contents of array don't change, use string literal types instead: type MyType = 'a' | 'b' | 'c' – felix-b Jun 04 '19 at 10:23

0 Answers0