TypeScript编译器API:当返回类型为数组时getReturnTypeOfSignature()的意外行为
假设以下组件类具有一个公共方法TypeScript编译器API:当返回类型为数组时getReturnTypeOfSignature()的意外行为,api,typescript,Api,Typescript,假设以下组件类具有一个公共方法get_id(),该方法返回一个文本值数组(此处:number[]): 只要该方法返回数组以外的任何内容,以下代码就可以正常工作: const componentSymbol: ts.Symbol = checker.getSymbolAtLocation( componentNode.name ) // componentNode is the AST node of the component class const componentType: ts.Type
get_id()
,该方法返回一个文本值数组(此处:number[]
):
只要该方法返回数组以外的任何内容,以下代码就可以正常工作:
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_id()
返回一个数组,returnType
等于:
{
flags: 1,
id: 4,
intrinsicName: "unknown"
}
基本上没有信息表明这应该是一个数字数组
另外,checker.typeToString(checker.getTypeAtLocation(methodDeclaration))
的返回值是()=>any
。我希望它是()=>number[]
我在这里做错了什么?我对从
tsconfig.json
文件中读取的编译器选项进行了一些实验。原来是lib
选项导致了问题。当注释掉时,我得到了预期的结果(()=>number
)
签名声明是从哪里来的?它未声明或分配给。您正在调用checker.getSignatureFromDeclaration(声明[0]为ts.SignatureDeclaration)代码>不使用其返回类型?这个问题应该有一个明确的答案MVCE@RyanCavanaugh:谢谢你的回复。我已经更新了原来的帖子,我希望它现在更精确一点。
{
flags: 1,
id: 4,
intrinsicName: "unknown"
}
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
};