![](/img/trans.png)
[英]Is there a way to get the declared type of a property rather than the type of the assigned value in typescript
[英]How do you use the Typescript compiler's Typechecker to get the declared (alias) type, rather than the resolved type?
我意识到这有点晦涩,但也许其他人已经遇到过这个问题或者很了解 Typescript 编译器。 我正在使用 Typescript 的编译器 API 处理 Typescript 文件,基于这样的例子: https : //github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
想象一下,我在 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;
}
在上面链接的示例中,您可以看到这样定义的方法来提取有关符号的信息:
function serializeSymbol(symbol: ts.Symbol): DocEntry {
return {
name: symbol.getName(),
type: checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration))
};
}
当您在date: DateString
上运行checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration)
时date: DateString
符号,而不是返回DateString
,它返回string
。换句话说,您没有得到声明的类型别名,而是完全解析类型。在我的情况下,我想知道date
字段的类型是DateString
。有没有一种简单的方法来查找参数的声明类型而不是其解析类型?
不幸的是,由于“类型实习”,这不起作用。 见这里。
有效的是获取typeNode
的文本。 所以基本上从节点获取文本。 这是您可能适用于您的场景的工作示例:
// 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
顺便说一句,您可能想查看我一直在研究的这个库
ts-type-info
ts-simple-ast
ts-morph ,以防您没有看到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.