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?
typeofoperator itself?typeof elemin this case will return an object simply. It's not really compatible to TypeScriptinstanceofoperator. I'm not sure why I saidtypeof.instanceofthen? It seems to me you are trying to rewriteinstanceof? For that matter, all your custom function does isreturn a instanceof btypeofbut I'm interested in the type of argument here, as I've asked. I want to practice this case and find out how to create a function properly