Challenge
Looking for a solution to the following problem:
save<T>(x: T | T[]) {
if (x instanceof Array) {
// save array to database
} else {
// save entity to database
}
return x
}
// client code
let obj: SomeType = { // values here }
let result = save(obj) // confusion arises during compilation...
The issue lies in TypeScript's uncertainty about whether result
is expected to be singular or an array.
Inquiry
How can I modify the function to specify that:
- if given a singular parameter, TypeScript recognizes the output as singular
- if given an array parameter, TypeScript identifies the output as an array