Is there a way to search for an element within a readonly array union in TypeScript?
const areas = {
area1: {
adjacencies: [2, 3, 4, 5]
},
area2: {
adjacencies: [6, 7, 8]
}
} as const;
let area: keyof typeof areas;
if (Math.random() < 0.5) {
area = "area1";
} else {
area = "area2"
}
// Argument of type 'number' is not assignable to parameter of type 'never'
areas[area].adjacencies.includes(3);
I also tried indexOf
, but it didn't work either. And I found the includes
type is
ReadonlyArray<T>.includes(searchElement: never, fromIndex: number | undefined): boolean
.
I suppose the includes
type should be the union of the elements of two readonly arrays, like demonstrated below:
const areas = {
area1: {
adjacencies: [2, 3, 4, 5]
},
area2: {
adjacencies: [6, 7, 8]
}
} as const;
type ValueOf<T extends object> = T[keyof T];
type Values = ValueOf<ValueOf<typeof areas>>
type ElementUnion = Values[number];
let area: keyof typeof areas;
if (Math.random() < 0.5) {
area = "area1";
} else {
area = "area2"
}
areas[area].adjacencies.includes(3);
How can I apply ElementUnion
to includes
or indexOf
methods?
Here is the playground