最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论