TS2367: This condition will always return 'false' with any

Viewed 4184

I am having difficulty understanding why the compiler excludes null from the set of types possible for arg (or alternatively I do not understand the diagnostic message).

    static vetStringNullable(arg:any): string|null {
        if (typeof arg === 'string') {
            return arg;
        }
        if (typeof arg === 'null') {
            return arg;
        }
        throw TypeError('Vetted value is not of type string or null.');
    }

The above code yields the following compiler diagnostic:

TS2367: This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"null"' have no overlap.

Edit: In light of the accepted answer, I have changed the function as follows:

    static vetStringNullable(arg:any): string|null {
        if (typeof arg === 'string' || arg === null) {
            return arg;
        }
        throw TypeError('Vetted value is not of type string or null.');
    }
1 Answers

The error message you're getting is simply stating that null is not in the list of defined types. The reason for this is that there's no such thing as a null type in JavaScript/TypeScript.

console.log(typeof null); // "object"

On the other hand, there is an undefined type:

let a;
console.log(typeof a); // "undefined"
Related