I'm trying to force an argument of type number[]
to contain at least one element of value 9
.
So far I've got:
type MyType<Required> = { 0: Required } | { 1: Required } | { 2: Required };
declare function forceInArray<
Required extends number,
Type extends number[] & MyType<Required>
>(
required: Required,
input: Type
): void;
// should fail type-checking
forceInArray(9, []);
forceInArray(9, [1, 2]);
forceInArray(9, { 0: 9 });
// should type-check correctly
forceInArray(9, [9]);
forceInArray(9, [9, 9]);
forceInArray(9, [9, 2, 3, 4]);
forceInArray(9, [1, 9, 3, 4]);
forceInArray(9, [1, 2, 9, 4]);
forceInArray(9, [1, 2, 3, 9]);
But ofc the type MyType
won't include all possible indexes, so I'm trying to write that in some other way. { [index: number]: 9}
is not the good way to do that, since it requires all values to be set to 9
. I've also tried some combination of mapped types, with no success
How can I write MyType
so that it solves this problem?