user578895
user578895

Reputation:

typescript tuple refinement via the type of one tuple?

It seems that I can refine tuples with null checks (=== null), but I can't figure out how to refine them on type checks. Is this possible? ts playground

// refining against null works
declare function fooA(): [string, null] | [null, string];
function A() {
    const x = fooA();

    if (x[0] === null) {
        const y = x[1]; // y = string
    }
}

// attempting to refine based on type = string, fails
declare function isString(x: any): x is string;
declare function fooB(): [string, number] | [number, string];
function B() {
    const x = fooB();

    if (isString(x[0])) {
        const y = x[1]; // y = string | number
    }
}

Upvotes: 0

Views: 174

Answers (1)

Oblosys
Oblosys

Reputation: 15106

This is a design limitation. You can use values (e.g. null) to discriminate between union members and conditionally narrow the type, but you cannot use type guards to do this. See this TypeScript issue (it's about objects instead of tuples, but the mechanism is the same).

Upvotes: 1

Related Questions