[SOLVED] Get inferred type arguments from TypeScript compiler


This Content is from Stack Overflow. Question asked by Avin Kavish

I have the following type and function signature

type Ctor<T> = {
  new (): T

export function foo<T>(Ctor: Ctor<T>) {


class Bar { foo = 'what' }

foo(Bar) // inferred type of T is Bar

I trying to get the inferred type of T at the call site foo(Bar) using the compiler api. So far I’ve tried,

if (ts.isCallExpression(node)) { 
  const funcType = typeChecker.getTypeAtLocation(node.expression)

But this only gets the declared type of foo. It doesn’t have the type arguments passed to it at the call site. I’ve also tried,

if (ts.isCallExpression(node)) { 
  const args = node.typeArguments

But this is also empty, I think because the types are not explicitly passed.

So how do I get the inferred type of T at each call site?


You can get this information from the resolved signature:

if (ts.isCallExpression(node)) {
  const signature = checker.getResolvedSignature(node);
  if (signature != null) {
    // outputs -- (Ctor: Ctor<Bar>): void
    const params = signature.getParameters();
    for (const param of params) {
      const type = checker.getTypeOfSymbolAtLocation(param, node);
      // outputs -- Ctor<Bar>

Answered by David Sherret, This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5.CC BY-SA 3.0.CC BY-SA 4.0.

people found this article helpful. What about you?