Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot extend native Error class #7639

Closed
iby opened this issue Mar 22, 2016 · 6 comments
Closed

Cannot extend native Error class #7639

iby opened this issue Mar 22, 2016 · 6 comments
Labels
Duplicate An existing issue was already created

Comments

@iby
Copy link

iby commented Mar 22, 2016

class FooError extends Error {
    constructor(message:string) {
        super(message);
    }
}
console.log((new FooError('foo')).message); // <nothing>
console.log((new Error('bar')).message); // bar

Am I missing something obvious or is there a bug with 1.8.9?

@mhegazy
Copy link
Contributor

mhegazy commented Mar 22, 2016

looks like a duplicate of #5069, please see the discussion in #1168 (comment)

@mhegazy mhegazy added the Duplicate An existing issue was already created label Mar 22, 2016
@mhegazy mhegazy closed this as completed Mar 22, 2016
@iby
Copy link
Author

iby commented Mar 22, 2016

I did. @ahejlsberg says:

Fixed by #3516. Classes can now extend arbitrary expressions of constructor function types.

Relevant PR contains an example:

class MyError extends Error { }

It compiles fine. What I'm trying to figure is why doesn't it work in compiled js?

@mhegazy
Copy link
Contributor

mhegazy commented Mar 22, 2016

it can. the compiler does not complain at you any more. the problem is not the TS compiler.

the problem here is that these classes are native, your runtime does not support extending them at the moment. In the future i would expect all these native types to be conformant with ES6 spec. @unional has a comment on how to get it to work with the engines today: #1168 (comment).

@unional
Copy link
Contributor

unional commented Mar 22, 2016

@mhegazy , wow, you got good memory. 👍

@iby
Copy link
Author

iby commented Mar 22, 2016

Ok, I feel a little awkward here, but that example doesn't compile:

'super' must be called before accessing 'this' in the constructor of a derived class. (17009)
Type 'Error | string' is not assignable to type 'Error'.

From what I can take from there, the suggested solution is to do this.message = message in the constructor?

@unional
Copy link
Contributor

unional commented Mar 22, 2016

The first line is a guard. You can take it out. The compiler has changed since then.

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants