Skip to content

Type guards ignored in closure #38755

@hgl

Description

@hgl

TypeScript Version:
v4.0.0-dev.20200523

Search Terms:
type guard closure
Code

let data: {[k: string]: string} = {}
function deleteOnClick() {
    let key = findKey()
    if (!key) {
        return;
    }
    let key2 = key
    window.addEventListener("click", () => {
        delete data[key2] // this is ok
        delete data[key] // type error, key can be null
    })
}

function findKey(): string | null {
    return null
}

Expected behavior:
delete data[key] contains no error
Actual behavior:
delete data[key] contains type error

Playground Link:
https://www.typescriptlang.org/play/?#code/DYUwLgBAJghmMC4IG8DaBrJBnMAnAlgHYDmAutnkcQL4QC8K1AUAGYCuhAxmPgPaHQQoMCADyhAMLB8ndAAoAlCiYRVEYRHQgAnvQgsiUANI7FKtfhYQ5AQi3alyc2rW5wbXIQDcziMxca9gBMeva+AO6GvOEAdDBQUACiAG4ghGAAMvg4aSC4cgBEnNKyBQA01kp0AHzKLi5QQuAg0HAwGDpBpBAA9D0QYAAW2RAjvOi+DU0irfAd2t19A9oADi15uLy4FfYQnDACAEYthGzAwL7UCkzMrBzcfAIGhMamChQEJBAAPhCn53VXO5PH8zhdqEA
Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions