doberkofler
doberkofler

Reputation: 10341

TypeScript type error with type string|number|null but not with string|number

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;
}

Upvotes: 0

Views: 489

Answers (1)

Matt H
Matt H

Reputation: 1973

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;
}

Upvotes: 1

Related Questions