microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.31k stars 12.39k forks source link

Class constructors that early return another object still require fields to be assigned #60025

Open TheCactusBlue opened 12 hours ago

TheCactusBlue commented 12 hours ago

🔎 Search Terms

"constructor flow analysis", "constructor early return"

🕗 Version & Regression Information

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.7.0-dev.20240922&ssl=15&ssc=1&pln=1&pc=1#code/MYGwhgzhAEBiD29oG8BQ0PQCZgC5gC5oJcAnASwDsBzAblXU2HkpNIFdhd5SAKHfAH4ibKtQCUKRpkzkAZtF4BCAWEloZmzAHpt0XAAtyEAHSrs8AKYxK8XNEqXLWfUgBGl6JAjlqjlwaWpJbSWjp6kNDkuADkMGAgwWBYAJ5eUL7+0CzQACIAorAAggCqADIAKgD6sADytaFh0MG47KSUeYWllTX19E0Avo2YhsZmeGDQALzYE-2YQ0OozKz2BcXl1XW10w6WAO5wiLwxuZZyYOwg9gjwMeL0QA

💻 Code

class Foo {
    data: string;

    constructor(data?: string) {
        if (!data) {
            // this.data does not need to be assigned here
            // as it's already assigned on DEFAULT_FOO
            return DEFAULT_FOO;
        }
        this.data = data;
    }
}

const DEFAULT_FOO = new Foo('Default Foo');

🙁 Actual behavior

Property 'data' has no initializer and is not definitely assigned in the constructor.

🙂 Expected behavior

No error messages

Additional information about the issue

No response

jcalz commented 12 hours ago

Duplicate #27555