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

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
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With