Skip to content

if(value!=null) doesn't narrow type in some situations #31050

Closed
@mysticatea

Description

@mysticatea

TypeScript Version: 3.5.0-dev.20190420

Search Terms: narrowing strictNullChecks

Code

type Box<T extends string> = { [key in T]: number | null }

function test1<T extends string>(key: T, { [key]: value }: Box<T>): number {
    if (value != null) {
        return value //ERROR: Type 'null' is not assignable to type 'number'.
    }
    return 0
}

function test2<T extends string>(key: T, box: Box<T>): number {
    if (box[key] != null) {
        return box[key] //ERROR: Type 'null' is not assignable to type 'number'.
    }
    return 0
}

Expected behavior:

In the block of if (value != null) {...}, the value is considered as non-null.

Actual behavior:

In the block of if (value != null) {...}, the value is considered as nullable.

Playground Link: https://www.typescriptlang.org/play/index.html#src=type%20Box%3CT%20extends%20string%3E%20%3D%20%7B%20%5Bkey%20in%20T%5D%3A%20number%20%7C%20null%20%7D%0D%0A%0D%0Afunction%20test1%3CT%20extends%20string%3E(key%3A%20T%2C%20%7B%20%5Bkey%5D%3A%20value%20%7D%3A%20Box%3CT%3E)%3A%20number%20%7B%0D%0A%20%20%20%20if%20(value%20!%3D%20null)%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20value%20%2F%2FERROR%3A%20Type%20'null'%20is%20not%20assignable%20to%20type%20'number'.%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20return%200%0D%0A%7D%0D%0A%0D%0Afunction%20test2%3CT%20extends%20string%3E(key%3A%20T%2C%20box%3A%20Box%3CT%3E)%3A%20number%20%7B%0D%0A%20%20%20%20if%20(box%5Bkey%5D%20!%3D%20null)%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20box%5Bkey%5D%20%2F%2FERROR%3A%20Type%20'null'%20is%20not%20assignable%20to%20type%20'number'.%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20return%200%0D%0A%7D%0D%0A

(please turn strictNullChecks option on.)

Related Issues:

Maybe #22137 is related.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions