Issue
I have a function myFunc<T1, T2 = undefined>
that returns [T1]
if T2 extends undefined
else [T1, T2]
. Is it possible to make such a function without // @ts-ignore
?
function myFunc<T1, T2 = undefined>(t1: T1, t2?: T2): T2 extends undefined ? [T1] : [T1, T2] {
if (t2 === undefined) {
return [t1];
}
return [t1, t2];
}
This syntax gives me a TypeScript error on each return
statement, saying the value is not assignable to T2 extends undefined ? [T1] : [T1, T2]
.
Solution
Conditional types usually cause problems in the implementation. You can't assign anything to a conditional type that still has unresolved type parameters except something of the exact same conditional type. So typescript will not let you assign [T1]
or [T1, T2]
to the return value.
You can use a type assertion, or you can use a separate implementation signature, one that returns a union. I personally prefer this second option:
function myFunc<T1, T2 = undefined>(t1: T1, t2?: T2): T2 extends undefined ? [T1] : [T1, T2]
function myFunc<T1, T2 = undefined>(t1: T1, t2?: T2): [T1] | [T1, T2] {
if (t2 === undefined) {
return [t1];
}
return [t1, t2];
}
Answered By - Titian Cernicova-Dragomir
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.