My scenario involves a union type of an Array with specific lengths:
[ number ] | [ number, number ] | [ number, number, number, number ]
The requirements are for an array with either one element, two elements, or four elements.
I am attempting to create an object that contains a function with one of these lengths. How should I write the type definition to accommodate this?
For example:
const people: {
name: string,
address: Address,
work: (numbers: [ number ] | [ number, number ] | [ number, number, number, number ]) => any
}[] = [
{
name: "Bob",
address: new Address(),
work: function(numbers: [ number ]): number {
// Implementation returning number
}
},
{
name: "Ashley",
address: new Address(),
work: function(numbers: [ number, number, number, number ]): boolean {
// Implementation returning boolean
}
},
{
name: "Michael",
address: new Address(),
work: function(numbers: [ number, number ]): number {
// Implementation returning number
}
},
]
Currently, I am encountering this error:
https://i.sstatic.net/y45gY.png
Type '(numbers: [number]) => number' is not assignable to type '(numbers: [number] | [number, number] | [number, number, number, number]) => any'. Types of parameters 'numbers' and 'numbers' are incompatible. Type '[number] | [number, number] | [number, number, number, number]' is not assignable to type '[number]'. Type '[number, number]' is not assignable to type '[number]'. Source has 2 element(s) but target allows only 1.ts(2322)
------- Edit -------
Following a suggestion from the comments, I have separated all the possible function calls into distinct function unions instead of an array union:
const people: {
name: string,
address: Address,
work: ((numbers: [ number ]) => any) | ((numbers: [ number, number ]) => any) | ((numbers: [ number, number, number, number ]) => any)
}[] = [
Now, when attempting to call a function from this array:
people[1].work([2, 8, 6, 4])
An error is now thrown:
https://i.sstatic.net/eyZW2.png
In VSCode, I discovered the reason for this:
"The intersection '[number] & [number, number] & [number, number, number, number]' was reduced to 'never' because property 'length' has conflicting types in some constituents."