Home > Enterprise >  TypeScript - Determine allowed array values from multiple arrays in object
TypeScript - Determine allowed array values from multiple arrays in object

Time:03-28

I have object with multiple arrays of strings (hardcoded). In other empty array I want to specify that only strings from that object are allowed.

In simple not nested I'm doing this with typeof someArray[number][] so I hoped that with nested array this will work typeof someObjectWithArrays[string][number][] but no :/

I thing this example will explain better what I mean:

const demo1 = ['test1', 'test2', 'test3'] as const
const demo2 = {
  a: ['test4', 'test5', 'test6'],
  b: ['test7', 'test8', 'test9'],
} as const

const values = {
  demo1: [] as typeof demo1[number][], // allow 'test1' 'test2' 'test3'
  demo2: [] as typeof demo2[string][number][], // ????? allow 'test4' 'test5' 'test6' 'test7' 'test8' 'test9'
}

console.log(values.demo1.includes('test1')) // ok
console.log(values.demo1.includes('notexists')) // error, so ok

console.log(values.demo2.includes('test8')) // ????? should be ok
console.log(values.demo2.includes('notexists')) // ????? should be error

Playground

CodePudding user response:

You need to change the index of typeof demo2 to be keyof typeof demo2:

const demo1 = ['test1', 'test2', 'test3'] as const
const demo2 = {
  a: ['test4', 'test5', 'test6'],
  b: ['test7', 'test8', 'test9'],
} as const

const values = {
  demo1: [] as typeof demo1[number][],
  demo2: [] as typeof demo2[keyof typeof demo2][number][],
}

console.log(values.demo1.includes('test1')) // ok
console.log(values.demo1.includes('notexists')) // error, so ok

console.log(values.demo2.includes('test8')) // correctly ok
console.log(values.demo2.includes('notexists')) // correctly errors

TypeScript Playground Link

  • Related