Reputation: 748
I want to create an assert function with TypeScript which will tell me if an element is an instance of, for example, an HTMLElement.
I'm trying to build it like this:
function assertIntanceOf(
element: unknown,
prototype: ??? // which type should I place here?
): boolean {
return element instanceof prototype;
}
and it must work like this:
const elem = document.querySelector('.someClass'); // returns an elem
assertInstanceOf(elem, HTMLElement); // returns true
const elem2 = document.querySelector('.someClassWhichNotExists'); // returns null cause elem with class .someClassWhichNotExists doesn't exist
assertInstanceOf(elem, HTMLElement); // returns false
const someVar = 123; // simply a number
assertInstanceOf(someVar, HTMLElement); //returns false
const someObj = { //just an object
a: 'abc'
}
assertInstanceOf(someVar, HTMLElement); //returns false
Which type should I place for prototype
argument?
Upvotes: 2
Views: 684
Reputation: 122116
I would make this generic, using the new()
"construct signature" per the FAQ, and return a type predicate so that using it will actually narrow the type of the first argument:
function assertInstanceOf<T>(
element: unknown,
prototype: { new(): T },
): element is T {
// ...
}
That said, TypeScript already knows about instanceof
type guards, so you don't necessarily need to put this in a function.
Upvotes: 3