Unfortunately in Typescript 4.5.4 the following overload with different tuples of different length does not work for me:
export function f<T1> (t: [T1]) : any { ... }
export function f<T1,T2> (t: [T1,T2]): any { ... }
while the usage would be (in another file)
f(["hello"])
f(["hello", "world"])
Typescript gives me:
TS2323: Cannot redeclare exported variable 'f'.
Any ideas on a workaround without introducing multiple function names (on top level)?
This question is similar, but the answer does not seem to work anymore and is not exactly the same (in my question Tuple type is given which may or may not have impact on the right answer).
CodePudding user response:
I'm not sure you need the extra overhead of overloads, but the answer you linked to still holds – overloads should declare multiple type signatures but only implement the function once.
export function f<T1>(t: [T1]): T1
export function f<T1, T2>(t: [T1, T2]): T2
export function f(t: [unknown] | [unknown, unknown]) {
if (t.length === 2) {
return t[1]
}
return t[0]
}
f([true]) // function f<boolean>(t: [boolean]): boolean ( 1 overload)
f([1, 'red']) // function f<number, string>(t: [number, string]): string ( 1 overload)
f([1, 'red', 2])
// ^^^^^^^^^^^^^
// No overload matches this call.
// Overload 1 of 2, '(t: [unknown]): unknown', gave the following error.
// Argument of type '[number, string, number]' is not assignable to parameter of type '[unknown]'.
// Source has 3 element(s) but target allows only 1.
// Overload 2 of 2, '(t: [unknown, unknown]): unknown', gave the following error.
// Argument of type '[number, string, number]' is not assignable to parameter of type '[unknown, unknown]'.
// Source has 3 element(s) but target allows only 2.
