0

The following code will alert undefined

class Parent {
    field: string
    constructor() {
       alert(this.field)
    }
}


class Child extends Parent {
    field = 'child'
}

new Child() #=> undefined

whereas, the following alerts 'child' as expected

class Parent {
    field: string
    constructor() {
       alert(this.field)
    }
}


class Child extends Parent {
    field = 'child'
    constructor() {
       // without referencing this.field before super(), this.field stays undefiend
       this.field
       super()
    }

}

new Child() #=> 'child'

Is there any ways to accomplish the following conditions?

  1. omit the whole Child's constructor declaration like the first example
  2. grab the member variable in Child class?

3 Answers 3

2

What jumps to mind is:

class Parent {
    constructor(public field: string) {
       alert(this.field)
    }
}


class Child extends Parent {
    constructor() {
       super('child');
    }

}

new Child() #=> 'child'

This doesn't meet your conditions but I feel it is fairly compact.

Sign up to request clarification or add additional context in comments.

Comments

2

Well you could defer the property access to a micortask:

 class Parent {
   field: string
   constructor() {
     Promise.resolve().then(() => {
        alert(this.field)
     };
   }
 }

But while that fullfills your conditions, it is ... still the wrong approach. Pass field as a constructor argument, as other answers show.

1 Comment

woh right, the only option technically meets the conditions, but will stick to the answer above. thanks
1

There's no way to accomplish your conditions, i'm pretty sure.

Grabbing the member variable in sub class happens after the base class constructor runs, and calling super() must be the first statement in a sub class constructor.

class Child extends Parent {
    field = 'child';
}
// the above is equal to:
class Child extends Parent {
    constructor(){ super(); this.field = 'child'; }
}

And this would cause error:

class Child extends Parent {
    constructor(){ 
        this.field = 'child'; // ERROR!
        super(); 
    }
}

2 Comments

somehow typescript playground parsed something like ``` function Child() { var _this = this; _this.field = 'child'; _this.field; _this = _super.call(this) || this; return _this; } ``` when putting this.field before super()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.