Typescript: instanceof not working

Created on 14 Mar 2018  Â·  7Comments  Â·  Source: microsoft/TypeScript

index.ts

class HttpError extends Error {

}

console.log(new HttpError() instanceof HttpError);

transpiled with tsc index.ts
run with node index.js
output:

false

```sh
tsc -v 2.6.2

tsconfig.json
```json
{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "declaration": true,
        "outDir": "./dist",
        "moduleResolution": "node",
        "noImplicitAny": true,
        "noUnusedLocals": true,
        "lib": ["es6", "dom"]
    }
}

expected output to be true

Duplicate

Most helpful comment

This is truly awful...

All 7 comments

https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work

This is truly awful...

@felangel You should reopen this. The workaround isn't a suitable fix.

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

I have the same problem here and it gave me a headache when I tried this after working around 3 hours at midnight :

class MissingError extends Error {
   constructor() {
        super('Missing Data');
        Object.setPrototypeOf(this, MissingError.prototype);
   }
}
console.log(new MissingError() instanceof MissingError) // false

I also experienced this extremely annoying issue. Essentially the "fix"
was ensure that native classes are not transpiled. This means to only
support ES2015, ES6 and above :-/

On Sun, Apr 7, 2019 at 4:32 PM Seyed Ali Roshan notifications@github.com
wrote:

I have the same problem here and it gave me a headache when I tried this
after working around 3 hours at midnight :

class MissingError extends Error {
constructor() {
super('Missing Data');
Object.setPrototypeOf(this, MissingDataError.prototype);
}
}
console.log(new MissingError() instanceof MissingError) // false

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/Microsoft/TypeScript/issues/22585#issuecomment-480642323,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABL5ZyJ46FqyI6XJRmfAOwHPjKYDV6Lpks5ven_3gaJpZM4SrPmZ
.

I was having this issue as well, but managed to solve it by removing the lib option and use the following configuration. I'm using typescript 3.9.5

"compilerOptions": {
    "target": "ES2015",
    "module": "CommonJS"
  }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

manekinekko picture manekinekko  Â·  3Comments

DanielRosenwasser picture DanielRosenwasser  Â·  3Comments

MartynasZilinskas picture MartynasZilinskas  Â·  3Comments

remojansen picture remojansen  Â·  3Comments

dlaberge picture dlaberge  Â·  3Comments