2

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?

6
  • Why not just use the typeof operator itself? Commented Feb 9, 2021 at 12:17
  • @VLAZ typeof elem in this case will return an object simply. It's not really compatible to TypeScript Commented Feb 9, 2021 at 12:21
  • Sorry, I meant the instanceof operator. I'm not sure why I said typeof. Commented Feb 9, 2021 at 12:22
  • Why not simply instanceof then? It seems to me you are trying to rewrite instanceof? For that matter, all your custom function does is return a instanceof b Commented Feb 9, 2021 at 12:23
  • @VLAZ I can use typeof but 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 Commented Feb 9, 2021 at 12:24

1 Answer 1

3

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 {
  // ...
}

Playground

That said, TypeScript already knows about instanceof type guards, so you don't necessarily need to put this in a function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.