Skip to content

Failure to refine tuple union return type when destructuring #32639

@jaredh159

Description

@jaredh159

TypeScript Version: 3.5.1

Search Terms:
destructure tuple destructuring

Code

function tuple(): [null, string] | [string, null] {
    if (Math.random() < 0.5) {
        return [null, 'a string'];
    }
    return ['a string', null];
}

const arr = tuple();

if (arr[0] === null) {
    arr[1].toUpperCase(); // <-- 👍 Works! TS knows arr[1] is a string
}

const [a, b] = tuple();

if (a === null) {
    b.toUpperCase(); // <-- 🚨 Error! TS doesn't know b is a string
}

Expected behavior:
TS can refine the destructured variables based on the function union return type.

Actual behavior:
Error.

It makes sense that when I do

const [a, b] = tuple();

That at that point, a and b need to both have an inferred type of null | string.

But when inside the conditional check if (a === null) I was expecting type refinement. Maybe that's an impossibility, but TS has gotten so smart I was genuinely surprised it wasn't able to refer that b was a string at that point.

Playground Link:
https://www.typescriptlang.org/play/#code/GYVwdgxgLglg9mABFEAHANgUwBQEoBciA2mCOugDSIDOUATjGAOYC6iAPsbQ81aeWwDeAKERjEMYImwBZAIZQAFgDo6csABM4AWzyIAPIgAMygKy5EI8dcR1MKOkhJlKiAORya9RkzcsA3KLiAL5BYnYOTh5ePL58LgHCocIQCLSIcnR0iAC8yGhYeIHCktKZdERGbDk1iPzoFlbi5UQAjCzKUHAAqqiomHQAwnLUOLiByalg6URyVABG1fkYY8Wl2J41efWNYYjznT19A8OjRUlAA

Related Issues:
maybe #28311 ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions