TypeScript Compiler API:当返回类型是数组时,getReturnTypeOfSignature()的意外行为

时间:2018-06-08 15:53:15

标签: api typescript

假设以下具有公共方法get_ids()的组件类返回一个文字值数组(此处为:number[]):

class Component {
  private _ids: number[];
  public get_ids() {
    return this._ids;
  }
}

只要方法返回除数组之外的其他内容,以下代码就可以正常工作:

const componentSymbol: ts.Symbol = checker.getSymbolAtLocation( componentNode.name ) // componentNode is the AST node of the component class
const componentType: ts.Type = checker.getDeclaredTypeOfSymbol( componentSymbol );

const property: ts.Symbol = componentType.getProperties[1]; // 2nd property represents the method 'get_ids()'
const methodDeclaration = property.getDeclarations()[0] as ts.MethodDeclaration;
const signature = checker.getSignatureFromDeclaration( methodDeclaration );
const returnType = checker.getReturnTypeOfSignature( signature );

但是,由于get_ids()返回一个数组,returnType等于:

{
  flags: 1,
  id: 4,
  intrinsicName: "unknown"
}

基本上没有信息表明这应该是一组数字。

此外,checker.typeToString(checker.getTypeAtLocation(methodDeclaration))的返回值为() => any。我希望它是() => number[]

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

我已经使用tsconfig.json文件中读入的编译器选项进行了一些实验。事实证明lib选项会导致问题。当注释掉时,我得到了预期的结果(() => number)。

const compilerOptions = {
    allowJs: false,
    checkJs: false,
    diagnostics: false,
    inlineSourceMap: true,
    inlineSources: true,
    jsx: ts.JsxEmit.React,
    // lib: [
    //     // "es5",
    //     // "dom",
    //     // "scripthost",
    //     // "es2015.iterable"
    // ],
    module: ts.ModuleKind.AMD,
    noEmitHelpers: true,
    strictNullChecks: false,
    tripInternal: true,
    target: ts.ScriptTarget.ES5,
    downlevelIteration: true,
    baseUrl: "./",
    pretty: true,
    experimentalDecorators: true
};