I'm currently using TypeScript 2.5.3 Compiler API. I can update to 2.6.x if it helps. I am trying to figure out how to get the TypeNode for the parent class. I thought I could use the TypeChecker, but haven't figured it out. Here is some relevant parts from the Mocha index.d.ts:
export class Base {
constructor(runner: IRunner);
}
export class Doc extends Base { }
While reading the ClassDeclaration I have access to its HeritageClauses. Each HeritageClause is an ExpressionWithTypeArguments, which is a TypeReferenceType. How do I get the ClassDeclaration of Base?
This is for https://github.com/fable-compiler/ts2fable/issues/83
2017-11-17 Friday update, here is example TypeScript. This outputs:
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
}
}
}