Skip to content

never-returning branches should not be considered when determining whether a property is initialized in a constructorΒ #56362

Closed as not planned
@ssalbdivad

Description

@ssalbdivad

πŸ”Ž Search Terms

constructor, initialization, initialized, 2564, never, throw, error

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

https://tsplay.dev/w6Q9yW

πŸ’» Code

const throwParseError = (def: unknown): never => {
    throw new Error(`${def} is not a valid definition`)
}

class Foo {
    // Property 'bar' has no initializer and is not definitely assigned in the constructor.(2564)
    bar: string

    constructor(def: string | null) {
        if (def === null) {
            // this return pattern is useful for narrowing
            // if you remove `return` here, the initialization error goes away
            // but the assignment to bar is then an error
            return throwParseError(null)
        }
        this.bar = def
    }
}

πŸ™ Actual behavior

TypeScript reports that Property 'bar' has no initializer and is not definitely assigned in the constructor.(2564)

πŸ™‚ Expected behavior

TypeScript should identify that in every viable branch of the constructor, bar is assigned.

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions