-
Notifications
You must be signed in to change notification settings - Fork 13k
Description
TypeScript Version: 3.8.0-dev.20191123
Search Terms: ambient declare public class fields parent initializer useDefineForClassFields
Code:
// @useDefineForClassFields: true
class Parent {
a: any;
constructor(arg: any) {
this.a = arg;
}
}
class Child extends Parent {
declare a: number;
constructor(arg: number) {
super(arg);
console.log(this.a); // Property 'a' is used before being assigned. (2565)
}
}
Expected behavior:
There should be no compile-time error, because this is legitimate ES(next) code. The intent of declare <field>
is merely to specialize the type, not to impose additional initialization constraints.
Actual behavior:
The usage of this.a
causes the compiler error Property 'a' is used before being assigned. (2565)
.
The emitted code is good. The only problem is the compile-time error.
Playground Link:
Related Issues: #34972
The main use-case for ambient public fields is to specialize parent class fields. It is common for parent class fields to only be initialized in the parent constructor, invoked via super()
. Due to this bug, this pattern does not work today, forcing the use of a workaround such as using @ts-ignore
or redundant re-initialization of the property in the child constructor to appease the compiler.
cc: @sandersn