Skip to content

Initialization of property in base class not recognized by sub class after redefinition #35831

Closed
@Pandawan

Description

@Pandawan

TypeScript Version: 3.7.3

Search Terms: extends, constructor, class, overriding, assigned, properties, jsdoc, documentation

I'm not sure if this is an actual bug as this is related to #1617 but is not exactly the same case.

I have a base class and a sub class which extends the base one. My goal is to override the JSDoc of one of the base's properties but keeping everything else intact. So I simply thought of declaring the exact same property on the subclass and change the JSDoc:

Code

class BaseClass {
    /**
     * Val in base
     */
    public val: number;
    constructor() {
        this.val = 5;
    }
}
class SubClass extends BaseClass {
    /**
     * Val in sub
     */
    public val: number;
    constructor() {
        super();
    }
}

Expected behavior: I'd expect everything to work since the constructor of the base class already sets val to 5 and is clearly called in the constructor.

Actual behavior: I get a Property 'val' has no initializer and is not definitely assigned in the constructor. ts(2564) in the sub class.

In a way, this makes sense because this error refers to val of the subclass, which isn't being assigned. But at runtime, everything will work fine (thanks to the prototype chain).

If this is intended, I'd like to know if there's any way to achieve the same result but without having to re-assign val inside the constructor. Essentially, I just want to replace the JSDoc of val in the sub class.

Playground Link: https://www.typescriptlang.org/play/?ts=Nightly#code/MYGwhgzhAEBCkFMDC4rQN4Cho+gegCoDtdoDoA1MEaASwDtoAjRE3AvN6ABwFcmQtYNABu1AFzR6vALZMEAJwDcXYAHt6EAC4LewLWoUAKAJQYupLQAtaEAHRiaAXmgBWFaQC+mb6EgwAZX4Uf2gEAA8tBHoAExh4CGRUGCxSQmJSMkpqOkYIfgsOLj4BIVEJKVl5ZVUNbV19Q1NzTNx87kVTD1xvTyA

Related Issues: #1617, #21775, #20911 (this issue might be a duplicate of one of these, sorry)

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions