Skip to content

TS2454 and var hoisting #19819

@spencerhakim

Description

@spencerhakim

TypeScript Version: 2.6.1

Code
I have some code vaguely similar to the following, which takes advantage of var hoisting; strictNullChecks is enabled:

if (input.a) {
    var a = doSomething(input.a); // returns a string
}
if (input.b) {
    var b = doSomethingElse(input.b); // returns a string
}
if (input.c) {
    var c = doAThirdThing(input.c); // returns a string
}

let options = {
    a, // error TS2454: Variable 'a' is used before being assigned
    b, // error TS2454: Variable 'b' is used before being assigned
    c // error TS2454: Variable 'c' is used before being assigned
};

Expected behavior:
a, b, and c should probably have implicit types of string | undefined, and no errors should be thrown.

Actual behavior:
a, b, and c have implicit types of string, and TS2454 is thrown.


For the moment, explicitly setting the types with var a: string | undefined = ... is a workaround, but I'm not a fan of how verbose that is, and I don't believe it should be needed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions