How do you extend a superclass property object in a subclass in JavaScript and get TypeScript to not complain? - Stack Overflow

Given this code:class Foo {data = { x: 1 };}class Bar extends Foo {override data = { ...super.data, y

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
Add a comment  | 

2 Answers 2

Reset to default 4

This 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); 

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745116455a4612155.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信