0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.