继承方法调用触发 Typescript 编译器错误
Inheritance method call triggers Typescript compiler error
我在使用 webstorm typescript 编译器时遇到问题。我有以下 classes
export class rootData{
id:string
//...
constructor(){
//...
}
insert = ():Promise<any> =>{
//...
}
}
class child extends rootData {
//...
constructor(){
super();
}
insert = ():Promise<any> => {
return super.insert();
}
}
因此键入 "super",我在智能感知中看到了所有 rootData public 方法。但是设置 super.insert() 后,出现以下错误:
TS2340:只有 public 和基 class 的受保护方法可通过 'super' 关键字访问
在 TS playground 上试过,可以用(简化版思想)。
感谢您的帮助。
编辑:检查编译后javascript,超级方法的调用就在那里。所以编译器报错但是编译...
因为 super
呼叫被重定向到 prototype
你不能使用 property
并且需要使用 method
即不能使用 = ()=>
.
固定代码:
export class rootData{
id:string
//...
constructor(){
//...
}
insert():Promise<any>{
//...
}
}
class child extends rootData {
//...
constructor(){
super();
}
insert():Promise<any> {
return super.insert();
}
}
您可以创建一个 "internal" 受保护的方法来实际执行逻辑。由于您不能在 class 之外调用它,因此 this 将始终处于正确的上下文中。
export class rootData{
id:string
//...
constructor(){
//...
}
insert = ():Promise<any> =>{
return this.insertInternal();
}
protected insertInternal():Promise<any>{
//...
}
}
class child extends rootData {
//...
constructor(){
super();
}
protected insertInternal():Promise<any> {
return super.insertInternal();
}
}
您可以查看它的 TypeScript Playgound 版本here。
我在使用 webstorm typescript 编译器时遇到问题。我有以下 classes
export class rootData{
id:string
//...
constructor(){
//...
}
insert = ():Promise<any> =>{
//...
}
}
class child extends rootData {
//...
constructor(){
super();
}
insert = ():Promise<any> => {
return super.insert();
}
}
因此键入 "super",我在智能感知中看到了所有 rootData public 方法。但是设置 super.insert() 后,出现以下错误:
TS2340:只有 public 和基 class 的受保护方法可通过 'super' 关键字访问
在 TS playground 上试过,可以用(简化版思想)。
感谢您的帮助。
编辑:检查编译后javascript,超级方法的调用就在那里。所以编译器报错但是编译...
因为 super
呼叫被重定向到 prototype
你不能使用 property
并且需要使用 method
即不能使用 = ()=>
.
固定代码:
export class rootData{
id:string
//...
constructor(){
//...
}
insert():Promise<any>{
//...
}
}
class child extends rootData {
//...
constructor(){
super();
}
insert():Promise<any> {
return super.insert();
}
}
您可以创建一个 "internal" 受保护的方法来实际执行逻辑。由于您不能在 class 之外调用它,因此 this 将始终处于正确的上下文中。
export class rootData{
id:string
//...
constructor(){
//...
}
insert = ():Promise<any> =>{
return this.insertInternal();
}
protected insertInternal():Promise<any>{
//...
}
}
class child extends rootData {
//...
constructor(){
super();
}
protected insertInternal():Promise<any> {
return super.insertInternal();
}
}
您可以查看它的 TypeScript Playgound 版本here。