0

I'd like to have a type which must receive an object that contains an array which contains the numbers 1 and 2 in their elements among other elements.

The definition would look something like this:

type Parent = {
  array: ReadonlyArray<number> & [...1] & [...2]
} 

So that any objects that use this type must contain the 2 elements.

const child1: Parent = { array: [1, 2] } // should work
const child2: Parent = { array: [1, 3, 4, 2] } // should work
const child3: Parent = { array: [0, 1, 2, 4] } // should work
const child4: Parent = { array: [1, 3, 4] } // should not work
const child5: Parent = { array: [1] } // should not work
  • Just to double-check: This is only for validating **literal** (or at least compile-time constant) arrays, right? Not `declare const someArrayFromElsewhere: number[]; const child6: Parent = { array: someArrayFromElsewhere };` Because types can't handle this at runtime, you need a runtime check for that. – T.J. Crowder Mar 11 '22 at 08:39
  • 1
    Yeah, it is meant to be a compile-time constraint.. – Bogdan Codreanu Mar 11 '22 at 08:43

0 Answers0