![](/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.