Repository navigation
Open
Labels
BugA bug in TypeScriptA bug in TypeScriptDomain: classesBehavior of various `class` constructs, e.g. mixins or base classesBehavior of various `class` constructs, e.g. mixins or base classes
Milestone
Description
🔎 Search Terms
TS2729, used before its initialization, declare, useDefineForClassFields
🕗 Version & Regression Information
- This changed between versions 4.2.3 and 4.3.5 (Consider class field properties to redeclare parent definitions #43194).
- It still reproduces in 6.0.3 and
7.1.0-dev.20261114.1. From 6.0 the default target enablesuseDefineForClassFields, so it reproduces with no options set.
⏯ Playground Link
💻 Code
(The Playground does not derive useDefineForClassFields from the target, so the link above enables it explicitly.)
class Base {
b: number = 1;
}
class Plain extends Base {
d = this.b; // OK
}
class Narrowed extends Base {
declare b: 1 | 2;
d = this.b; // error TS2729: Property 'b' is used before its initialization.
}
console.log(new Narrowed().d); // 1🙁 Actual behavior
this.b in Narrowed reports TS2729.
🙂 Expected behavior
No error, as in Plain. Per the spec, the base class's fields are initialized inside super(), and the derived class's fields right after super() returns (SuperCall evaluation). declare emits nothing, so b is already initialized (1) when d is initialized. #42319 also lists this as expected: "c is allowed because of the declare modifier".
Additional information about the issue
- Consider class field properties to redeclare parent definitions #43194 removed the ancestor-class exemption under
useDefineForClassFields, for the case where a redeclaration without an initializer (b;) overwrites the property withundefined(DefineField). It also catchesdeclareredeclarations, which emit nothing. The test it added covers only the case withoutdeclare. - TS2612 suggests adding
declareto such a redeclaration, and doing so produces this error. - The same error occurs with
declare context: React.ContextType<…>, as recommended by@types/react, when a field initializer readsthis.context. - Found while testing my own TypeScript compiler (https://github.com/mizchi/ts.mbt).
Metadata
Metadata
Assignees
Labels
BugA bug in TypeScriptA bug in TypeScriptDomain: classesBehavior of various `class` constructs, e.g. mixins or base classesBehavior of various `class` constructs, e.g. mixins or base classes
Activity
tsc-extra: record the filed issue for the declare-field case
Exempt declare redeclarations from TS2729 use-before-init check (micr…