dx_over_dt
dx_over_dt

Reputation: 14328

TypeScript return different type based on type arguments

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].

Upvotes: 1

Views: 135

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250266

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];
}

Upvotes: 1

Related Questions