Skip to content

Cannot extend native Error class #7639

Description

@iby
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?

Activity

  1. mhegazy commented on Mar 22, 2016

    @mhegazy
    Contributor

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

  2. iby commented on Mar 22, 2016

    @iby
    Author

    I did. Anders Hejlsberg (@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?

  3. mhegazy commented on Mar 22, 2016

    @mhegazy
    Contributor

    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. Homa Wong (@unional) has a comment on how to get it to work with the engines today: #1168 (comment).

  4. unional commented on Mar 22, 2016

    @unional
    Contributor

    Mohamed Hegazy (@mhegazy) , wow, you got good memory. 👍

  5. iby commented on Mar 22, 2016

    @iby
    Author

    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?

  6. unional commented on Mar 22, 2016

    @unional
    Contributor

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

  7. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions