Issue
Why I've got an error "Abstract property 'field0' in class 'SuperAbstractClass' cannot be accessed in the constructor", although if we look into the transpiled code we will understand that we have an access to this field or we can just run it in the ts playground to see that field1 is "default value"
abstract class SuperAbstractClass {
public abstract field0: string = 'default value';
public abstract field1: string;
}
abstract class SubAbstractClass extends SuperAbstractClass {
public field1: string = this.field0;
}
class SuboncreteClass extends SubAbstractClass {
public field0: string = '';
}
var a = new SuboncreteClass()
console.log(a);
Transpiled
"use strict";
class SuperAbstractClass {
constructor() {
this.field0 = 'default value';
}
}
class SubAbstractClass extends SuperAbstractClass {
constructor() {
super(...arguments);
this.field1 = this.field0;
}
}
class SuboncreteClass extends SubAbstractClass {
constructor() {
super(...arguments);
this.field0 = '';
}
}
var a = new SuboncreteClass();
console.log(a);
Solution
I like this question because I really had to dig around to see what's going on here. I'm very surprised that one is even allowed to initialize a property that's declared abstract
in the same class, but by microsoft/TypeScript#33356 it's intentionally supported (or at least there was no compelling enough reason to disallow it and possibly break existing code). Notice that if you try to implement an abstract method in the same way, it's considered an error:
abstract class ImplAbstractMethod {
abstract method() { } // error!
// Method 'method' cannot have an implementation because it is marked abstract
}
I'm not sure what your intent is, marking the property as abstract
but then having a concrete value for it in the same class, but that's up to you I guess.
In any case, the initialization is an internal implementation detail of the superclass and is not part of its declaration. That declaration would be like this:
declare abstract class DeclaredSuperAbstractClass {
public abstract field0: string;
public abstract field1: string;
}
You can't declare that an abstract class's property is initialized. Therefore, users of that superclass cannot know that field0
has been initialized; they only know that it's abstract
and therefore may not exist. So you get that error.
Personally I keep returning to the weirdness of initializing abstract properties. My suggestion is that, if your intent is to allow subclasses to access a value of field0
set in the parent class, you should remove the abstract
modifier from field0
, because you're not getting any benefit from it:
abstract class SuperAbstractClass {
public field0: string = 'default value';
public abstract field1: string;
}
abstract class SubAbstractClass extends SuperAbstractClass {
public field1: string = this.field0; // okay
}
Answered By - jcalz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.