【发布时间】:2017-11-19 05:54:26
【问题描述】:
我目前正在使用 TypeScript 2.5.3 编译器 API。如果有帮助,我可以更新到 2.6.x。我想弄清楚如何为父类获取TypeNode。我以为我可以使用TypeChecker,但还没有弄清楚。以下是 Mocha index.d.ts 中的一些相关部分:
export class Base {
constructor(runner: IRunner);
}
export class Doc extends Base { }
在阅读ClassDeclaration 时,我可以访问它的HeritageClauses。每个HeritageClause 是一个ExpressionWithTypeArguments,它是一个TypeReferenceType。如何获得Base 的ClassDeclaration?
这是给https://github.com/fable-compiler/ts2fable/issues/83
2017-11-17 周五更新,这里是 TypeScript 示例。这输出:
heritage clause: extends Base
contextual type: undefined
import * as ts from "typescript";
import * as fs from "fs";
const tsPath = "node_modules/@types/mocha/index.d.ts"
const options: ts.CompilerOptions = { target: ts.ScriptTarget.ES2015 }
const host = ts.createCompilerHost(options, true);
const program = ts.createProgram([tsPath], options, host)
const checker = program.getTypeChecker()
const sourceFile = program.getSourceFile(tsPath)
// console.log(sourceFile)
function visitNode(node: ts.Node){
switch (node.kind) {
case ts.SyntaxKind.ClassDeclaration:
const cd = (<ts.ClassDeclaration>node);
// console.log(cd.name.getText())
if(cd.name.getText() === "Doc"){
printBaseClass(cd)
}
}
ts.forEachChild(node, visitNode)
}
ts.forEachChild(sourceFile, visitNode);
function printBaseClass(cd: ts.ClassDeclaration){
// console.log(cd)
for(const hc of cd.heritageClauses) {
console.log("heritage clause: " + hc.getText())
for(const hctp of hc.types){
// hctp is a ts.ExpressionWithTypeArguments
const ct = checker.getContextualType(hctp.expression)
console.log("contextual type: " + ct) // undefined
}
}
}
【问题讨论】:
-
疯狂猜测:
ExpressionWithTypeArguments是TypeNode,所以也许你可以使用getTypeFromTypeNode?
标签: typescript typescript-compiler-api