Skip to content

"Used before initialization" error false positives and negatives with optional propertiesΒ #61785

Open
@aweebit

Description

@aweebit

πŸ”Ž Search Terms

used before its initialization

πŸ•— Version & Regression Information

⏯ Playground Link

https://www.typescriptlang.org/play/?useDefineForClassFields=true&ts=5.8.3#code/MYGwhgzhAEDC0G8BQ1XTNAvNALgCwEsIA6AIwG4U1SB+ALmgDsBXAW1IFMAnLaARgBMAZkoBfJElCQYAEURVUYBi3bdoAH2jNGAEw4AzAow47KaaKV74ixDNkEik4oA

πŸ’» Code

class C {
    a = this.b;
    b?: number = 123;
}

class D {
    a: number | undefined;
    b = this.a = 123;
}

πŸ™ Actual behavior

When initializing C.a: no error.

When initializing D.b:

Property 'a' is used before its initialization. (2729)

πŸ™‚ Expected behavior

When initializing C.a:

Property 'b' is used before its initialization. (2729)

When initializing D.b: no error.

Additional information about the issue

Tried with both useDefineForClassFields set to true and false.

The behavior is as expected when switching the use of undefined and the "optional" ? modifier like this:

class C {
    a = this.b;
    b: number | undefined = 123;
}

class D {
    a?: number;
    b = this.a = 123;
}

#43100 seems to have taken a wrong approach. Instead of basing the decision to report an error on whether the ? modifier is present, it should be based on whether the property access is on the left-hand side of an assignment expression.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions