Typescript: 'call on undefined' error when calling super from overwritten property function

Created on 5 Jun 2018  路  4Comments  路  Source: microsoft/TypeScript

TypeScript Version: 2.8.3, also whichever version powers playground


Search Terms:
Super function method property access cannot read property call of undefined

Code

class A {
    public myFunc = () => {
        return 'a';
    };
}

class B extends A {
    public myFunc = () => {
        return super.myFunc();
    };
}

const b = new B();
console.log(b.myFunc());

Expected behavior:
Either:

  • Prints 'a' to console (may not be possible based on related issues below?)
  • Compile time error

Actual behavior:
Successfully builds into JS which then fails at runtime

Uncaught TypeError: Cannot read property 'call' of undefined
    at B._this.myFunc (<anonymous>:24:44)
    at <anonymous>:31:15
    at HTMLButtonElement.excuteButton.onclick (https://www.typescriptlang.org/play/playground.js:247)

Playground Link: Link

Related Issues:

4465 and #338 seem related though they focus on getters and setters

Working as Intended

Most helpful comment

Don't use =>, you can write:

class A {
    public myFunc ()  {
        return 'a';
    };
}

class B extends A {
    public myFunc ()  {
        return super.myFunc();
    };
}

const b = new B();
console.log(b.myFunc());

All 4 comments

The runtime behavior itself seems appropriate. This is (more or less) the following equivalent code without class properties:

class A {
    constructor() {
        this.myFunc = () => {
            return 'a';
        };
    }
}

class B extends A {
    constructor() {
        super();
        this.myFunc = () => {
            return super.myFunc();
        };
    }
}

const b = new B();
console.log(b.myFunc());

I think what's problematic is that we don't differentiate between a property if it appeared on the prototype vs. on the instance, so we don't issue an error at all which is unfortunate.
and this will error in any runtime I've tried.

I tested with [email protected] and I still get a compile time error:

src/a.ts(9,22): error TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword.

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Don't use =>, you can write:

class A {
    public myFunc ()  {
        return 'a';
    };
}

class B extends A {
    public myFunc ()  {
        return super.myFunc();
    };
}

const b = new B();
console.log(b.myFunc());
Was this page helpful?
0 / 5 - 0 ratings

Related issues

weswigham picture weswigham  路  3Comments

siddjain picture siddjain  路  3Comments

zhuravlikjb picture zhuravlikjb  路  3Comments

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments