0

Why does the function foo report an error Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'. in the return value; line and the function bar works as expected?

TypeScript Playground

function foo(value: string | number | null): string | null {
    if (typeof value !== 'string' && value !== null) {
        throw new Error();
    }

    return value;
}

function bar(value: string | number): string {
    if (typeof value !== 'string') {
        throw new Error();
    }

    return value;
}

1 Answer 1

1

Your code doesn't throw a type error in Typescript 3.2.2 with strict null checks.

function foo(value: string | number | null): string | null {
    //value has type `string | number | null`
    if (typeof value !== 'string' && /*value has type `number | null` */ value !== null) {
        //value has type `number`
        throw new Error();
    }
    //value has type `string | null`

    return value;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I would exactly expect the types that you described but I’m 100% sure that I get a type error in the TypeScript Playground. Did you test it with my shared url?
It looks like the key factor is enabling strict null checks. It never really occurred to me that disabling strict null checking could actually cause type errors. When strict null checking is disabled, both string and number are basically treated like 'nullable' types. Therefore, checking for value !== null fails to isolate numbers in the type checking.
Actually quite confusing that without strict null checks a code that actually checks for null fails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.