Typescript: null checks are ignored in "unknown" narrowing

Created on 28 Mar 2020  路  4Comments  路  Source: microsoft/TypeScript


TypeScript Version: 3.8.3 Nightly playground


Search Terms:

Code

const func = (value: unknown) => {
    const results = [];

    // 1
    if (typeof value === 'object' && value !== null) {
        results.push(1); // (parameter) value: object
    }
    // 2
    if (value !== null && typeof value === 'object') {
        results.push(2); // (parameter) value: object | null
    }
    // 3
    if (typeof value === 'object') {
        if (value !== null) {
            results.push(3); // (parameter) value: object
        }
    }
    // 4
    if (value !== null) {
        if (typeof value === 'object') {
            results.push(4); // (parameter) value: object | null
        }
    }
    // 5
    results.push(5); // (parameter) value: unknown

    return results;
};

console.log(func({})); // [1, 2, 3, 4, 5]
console.log(func(null)); // [5]

Expected behavior:
2 and 4 shouldn't have null as expected type.

Actual behavior:
null checks are being ignored depending on the order they're in.

Duplicate

Most helpful comment

The core problem here is https://github.com/microsoft/TypeScript/issues/4196. The compiler has no way to express a type of Exclude<unknown, null> so the null check coming first does nothing.

However it seems 2) might be fixable as https://github.com/microsoft/TypeScript/issues/36709 was fixed.

All 4 comments

The core problem here is https://github.com/microsoft/TypeScript/issues/4196. The compiler has no way to express a type of Exclude<unknown, null> so the null check coming first does nothing.

However it seems 2) might be fixable as https://github.com/microsoft/TypeScript/issues/36709 was fixed.

@nmain is correct. We don't have any mechanism to produce a useful narrowing for unknown !== null, and CFA is naturally order-dependent.

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

It hasn鈥檛 been addressed if this has been fixed by https://github.com/microsoft/TypeScript/pull/37134 or not. Should this still be closed?

Was this page helpful?
0 / 5 - 0 ratings