[英]How do you use the Typescript compiler's Typechecker to get the declared (alias) type, rather than the resolved type?
I realize this is somewhat obscure, but maybe someone else has run into this or knows the Typescript compiler well.我意识到这有点晦涩,但也许其他人已经遇到过这个问题或者很了解 Typescript 编译器。 I am processing Typescript files using Typescript's compiler API, based on examples like this: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
我正在使用 Typescript 的编译器 API 处理 Typescript 文件,基于这样的例子: https : //github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
Imagine I have a declared function like this in Typescript:想象一下,我在 Typescript 中有一个这样的声明函数:
export type DateString = string;
export function parseDate(date: DateString): Date{
let parsedDate = Date.parse(date);
let retVal = new Date();
retVal.setTime(parsedDate);
return retVal;
}
In the examples linked above, you can see methods like this defined to extract information about symbols:在上面链接的示例中,您可以看到这样定义的方法来提取有关符号的信息:
function serializeSymbol(symbol: ts.Symbol): DocEntry {
return {
name: symbol.getName(),
type: checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration))
};
}
When you run checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration)
on the date: DateString
symbol, instead of returning DateString
, it returns string
. In other words, you don't get the declared type alias, but the fully resolved type. In my case, I'd like to know that the type of the date
field is DateString
. Is there an easy way to look up a parameter's declared type rather than its resolved type?当您在
date: DateString
上运行checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration)
时date: DateString
符号,而不是返回DateString
,它返回string
。换句话说,您没有得到声明的类型别名,而是完全解析类型。在我的情况下,我想知道date
字段的类型是DateString
。有没有一种简单的方法来查找参数的声明类型而不是其解析类型?
Unfortunately this doesn't work because of "type interning."不幸的是,由于“类型实习”,这不起作用。 See here .
见这里。
What works is to get the text of the typeNode
.有效的是获取
typeNode
的文本。 So basically get the text from the node.所以基本上从节点获取文本。 Here's a working example that you may be apply to your scenario:
这是您可能适用于您的场景的工作示例:
// fileToAnalyze.ts
type DateString = string;
function myFunction(date: DateString) {
}
// main.ts
import * as ts from "typescript";
import * as path from "path";
const program = ts.createProgram([path.join(__dirname, "fileToAnalyze.ts")], { });
const file = program.getSourceFiles().filter(f => /fileToAnalyze/.test(f.fileName))[0];
const funcNode = (file.statements[1] as ts.FunctionDeclaration);
const parameterNode = funcNode.parameters[0];
console.log(parameterNode.type.getText(file)); // DateString
By the way, you might want to check out this library
ts-type-info
ts-simple-ast
ts-morph that I've been working on in case you haven't seen it.顺便说一句,您可能想查看我一直在研究的这个库
ts-type-info
ts-simple-ast
ts-morph ,以防您没有看到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.