Given this code:
class Foo {
data = { x: 1 };
}
class Bar extends Foo {
override data = { ...super.data, y: 1 };
}
TypeScript complains on the super.data
part:
Class field 'data' defined by the parent class is not accessible in the child class via super.
And in practice, it doesn't even work.
console.log(new Foo().data)
// {x: 1}
console.log(new Bar().data)
// {y: 1}
Given this code:
class Foo {
data = { x: 1 };
}
class Bar extends Foo {
override data = { ...super.data, y: 1 };
}
TypeScript complains on the super.data
part:
Class field 'data' defined by the parent class is not accessible in the child class via super.
And in practice, it doesn't even work.
console.log(new Foo().data)
// {x: 1}
console.log(new Bar().data)
// {y: 1}
Share
Improve this question
edited Mar 2 at 22:48
Bergi
667k161 gold badges1k silver badges1.5k bronze badges
asked Mar 2 at 22:15
user29860985user29860985
2 Answers
Reset to default 4This has nothing to do with TypeScript, this is just how JavaScript class fields work. They are initialised by the constructor as part of each instance. They are not accessed via accessors on the prototype chain, they are own properties of the instance, so using super
does not make sense for them and your code wouldn't do what you expect (TypeScript saved you from making a mistake there).
Just write this.data
, but you have to persuade TypeScript that it doesn't refer to the property you're about to initialise:
class Foo {
data = { x: 1 };
}
class Bar extends Foo {
override data = { ...(this as Foo).data, y: 1 };
}
in typescript class fields are initialized per instance, and super.data isn't directly accessible in field initializers to correctly extend the data object move assignment to the contractor after invoke super()
The code should look like below:
class Foo {
data = { x: 1 };
}
class Bar extends Foo {
constructor() {
super();
this.data = { ...this.data, y: 1 };
}
}
console.log(new Bar().data);