Recently, TypeScript has introduced a compilation error, when user tries to override a property in the base class with getter/setter pair (property access augmentation):
class BaseClass {
prop : string = 'base_class'
}
class SubClass extends BaseClass {
_prop : string = 'sub_class'
/*
ERROR: 'prop' is defined as a property in class 'BaseClass', but is overridden here in 'SubClass' as an accessor.
*/
get prop () : string {
return this._prop
}
set prop (value : string) {
this._prop = value
}
}
// try running this snippet with `useDefineForClassFields : true` and `useDefineForClassFields : false`
console.log((new SubClass).prop)
This error is motivated by the fact, that in modern JavaScript, class fields have [[DEFINE]] semantic and the above example won't work as intuitively expected if useDefineForClassFields compiler option is set to true.
Need to note, that historically nobody was ever using the DEFINE semantic for class properties. Pretty much all the JavaScript and TypeScript code in the world currently assumes the SET semantic for class fields.
Property access augmentation pattern is perfectly valid with SET semantic. Its very idiomatic JavaScript. Its main use case is to trigger some arbitrary code on property read/write. This is very useful for variety of purposes and is done by simply overriding the property of the base class with getter/setter accessors pair.
TypeScript and JavaScript historically were using SET semantic for class fields. After the DEFINE semantic was introduced, TypeScript added the new compiler config, useDefineForClassFields, which controls the semantic of class fields and is disabled by default, because its a breaking change.
QUESTIONS:
useDefineForClassFields=false which is a default)See also: Proposal to limit the compilation error to DEFINE semantic only