55

I am working in a react app using typescript. One of the functions receives a generic type in one of the variables.

How can I check the type T of the variable? Is this possible?

MyFunction<T>(newValues: Array<T>) {
    if (typeof T === "string") {
        // do some stuff
    }
}
1
  • 7
    You cannot check for TypeScript types at runtime, since none of the type information exists in the compiled JS files. The only type-checking you can perform uses JavaScript’s typeof operator which accepts a variable, not a type Commented Feb 18, 2019 at 16:42

1 Answer 1

32

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!

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.