I need help writing two Jest functions that can verify if an object is an instance of a specific type or not.
The function expectInstanceOf
works perfectly, but unfortunately, the function expectNotInstanceOf
is not functioning as expected.
export function expectInstanceOf<E, A extends unknown[]>(obj: unknown, type: new (...args: A) => E): asserts obj is E {
expect(obj).toBeInstanceOf(type);
}
export function expectNotInstanceOf<E, A extends unknown[]>(obj: unknown, type: new (...args: A) => E): asserts obj is Exclude<typeof obj, E> {
expect(obj).not.toBeInstanceOf(type);
}
class Foo {
foo() {
/**/
}
}
class Bar {
bar() {
/**/
}
}
function foo(obj: Foo | Bar) {
expectInstanceOf(obj, Foo);
obj.foo();
}
function notFoo(obj: Foo | Bar) {
expectNotInstanceOf(obj, Foo);
obj.bar(); // Property 'bar' does not exist on type 'Foo | Bar'.
}
Is there a way to correct the functionality of expectNotInstanceOf
?