2

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?

4
  • The question is not clear: the inferred type of T is the type of the argument you're passing to the function, so you already know it. Can you show a full minimal example of what you've tried, and what you'd like to get? Commented Sep 19, 2022 at 11:36
  • It's not the type of the argument, in this example, type of the argument is typeof Bar but T is type Bar. So I cant directly get T by checking the type of the argument. Commented Sep 19, 2022 at 11:42
  • @Blackhole OP is trying to get the inferred type of the foo call (which should be foo<Bar>(Bar)) through the compiler API. The two attempts they have shown aren't successful. Commented Sep 19, 2022 at 14:02
  • 1
    I just added the "typescript-compiler-api" tag, to better categorize the question and, I hope, to make it more obvious that this isn't just a regular typescript question Commented Sep 19, 2022 at 16:09

1 Answer 1

3

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
    console.log(checker.signatureToString(signature));
    const params = signature.getParameters();
    for (const param of params) {
      const type = checker.getTypeOfSymbolAtLocation(param, node);
      // outputs -- Ctor<Bar>
      console.log(checker.typeToString(type));
    }
  }
}
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.