How do I determine the result type of a TypeScript

2019-02-20 14:48发布

问题:

When working with the TypeScript abstract syntax tree, how do I determine the result type of a TypeScript.Expression object?

I am using TSLint and attempting to find invocations of setTimeout that do not pass an object of type Function as the first parameter. For example, in the following code, I want to know that setTimeout was invoked and that the first parameter is a function.

// function that produces a function
var createFunction : () => (() => void) = () => {}; 
// result of createFunction() should be of type function
setTimeout(createFunction());

The AST lines up like this:

  • setTimeout -> TypeScript.CallExpression
  • createFunction() -> TypeScript.Expression

I have tried to use the LanguageService to determine the type of the Expression, but none of the following APIs give me what I need:

  • languageServices.getQuickInfoAtPosition
  • languageServices.getDefinitionAtPosition
  • languageServices.getTypeDefinitionAtPosition

Any ideas?

回答1:

The language service itself doesn't expose that information.

You can use the type checker to do this. Once you have a program object from createProgram, write:

        let typeChecker = program.getTypeChecker();
        let type = typeChecker.getTypeAtLocation(node);