Checking type of a generic param in typescript

Well, kind of possible. You can check for the type of objects during runtime using typeof type guards like in your example as long as the type of T is one of JavaScript’s primitive types (string, number, function, etc). Like so:

function printAll(strs: string | string[] | null) {
  if (typeof strs === "object") {
    for (const s of strs) {
      // Object is possibly 'null'.
      console.log(s);
    }
  } else if (typeof strs === "string") {
    console.log(strs);
  } else {
    // do nothing
  }
}

If T can be an object that you know how to identify, using type predicates would be a way to go. These are user defined functions that identify if an argument is of a specific type.

You can find more information on these two methods and a few more in the TypeScript Handbook, on the “Narrowing” chapter: https://www.typescriptlang.org/docs/handbook/2/narrowing.html

Keep in mind that you are checking for the types of the parameters, not the generic type T itself. Ideally, your function should work without knowing exactly what T is, and instead just using it as a placeholder for what T will be when the method is called.

You need to be careful, however, since type guards are used when trying to differentiate between two or more known types, not when determining the type of a generic.

Keep in mind that if you need to determine the type of a generic, you might not actually need a generic. If you know what are the possible types that a function could be called with, and those types matter, I’d suggest you look into union types.

It is not the intention of TypeScript to alter JavaScript at runtime, but instead to make it easier for tools and the developer to develop in JavaScript. All the magic of TypeScript should happen before the code is sent to the browser.

Hope that helps!

Leave a Comment