Skip to content

Instantly share code, notes, and snippets.

@vladima
Created April 22, 2016 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladima/a6d1b558a8d2b16446c9b04c1737ffb6 to your computer and use it in GitHub Desktop.
Save vladima/a6d1b558a8d2b16446c9b04c1737ffb6 to your computer and use it in GitHub Desktop.
import * as ts from "typescript";
const fileName = "test.ts";
const program = ts.createProgram([fileName], {});
const typeChecker = program.getTypeChecker();
const file = program.getSourceFile(fileName);
// use getSignatureFromDeclaration
{
const ctorDecl = ts.forEachChild(file, function find(n) {
return (n.kind === ts.SyntaxKind.Constructor && <ts.ConstructorDeclaration>n) || ts.forEachChild(n, find);
});
writeParameters(typeChecker.getSignatureFromDeclaration(ctorDecl));
}
// use getSignaturesOfType
console.log("=========")
{
const classDecl = <ts.ClassDeclaration>file.statements[0];
const constructorFunctionType =
typeChecker.getTypeOfSymbolAtLocation(
typeChecker.getSymbolAtLocation(classDecl.name),
classDecl
);
writeParameters(typeChecker.getSignaturesOfType(constructorFunctionType, ts.SignatureKind.Construct)[0]);
}
function writeParameters(sig: ts.Signature) {
for (const parameter of sig.getParameters()) {
console.log(`${parameter.getName()}: ${typeChecker.typeToString(typeChecker.getTypeOfSymbolAtLocation(parameter, parameter.valueDeclaration))}`);
}
}
class A {
constructor(a: number, b: string) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment