Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof not work correctly in typescript library project

I build a typescript library project. and use some classes from a public package.
let's say a simple function to test it is a BadRequestException or not

import { BadRequestException } from "@nestjs/common";
export function test(error) {
  let a = error;
  let b = BadRequestException;
  console.log(a instanceof b);
}

after build and import this shared-lib library from another normal project and i called like this

import { BadRequestException } from "@nestjs/common";
import { test } from 'shared-lib';
test(new BadRequestException('it is a test error'));

in my throught(it should be), a instance b in test function should be equals true,however,i got false

enter image description here

is that BadRequestException used in the library project is different from that in the second project, even both of them are imported from "@nestjs/common"?

uploaded a demo project in Github

like image 667
Kent Wood Avatar asked Oct 24 '25 15:10

Kent Wood


2 Answers

instanceof checks if the constructors are the same. The thing is that your code gets its own copy of the constructor from the code in the library (because that's how it is, it's not your fault), so they are not the same instance anymore.

The constructors still share the same name though:

error.constructor.name === BadRequestException.prototype.constructor.name

See related question here

like image 98
daign Avatar answered Oct 26 '25 05:10

daign


Using the accepted answer, you can create a narrowing function using type predicates.

E.g.:

const isBadRequestException = (error: any): error is BadRequestException => {
  return error.constructor.name === BadRequestException.prototype.constructor.name;
}

Then you can use this for subsequent typed access to the error object:

if (isBadRequestException(error)) {
  error... // Properties now available
}
like image 32
Oliver Avatar answered Oct 26 '25 04:10

Oliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!