Created
April 22, 2016 19:43
-
-
Save vladima/a6d1b558a8d2b16446c9b04c1737ffb6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))}`); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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