How to get type information of property declaration whose type is a class from another file?
// person.ts
/**
* @description Some description
*/
export class Person {
name: string;
constructor() { }
}
// group.ts
export class Group {
member1: Person; // <-- Use TS typechecker to get info of Person class
member2: Person;
element: HTMLButtonElement; // <-- Getting all member and nodes for HtmlButtonElement using typechecker
constructor() { }
}
Using TypeScript Compiler API
import ts from 'typescript';
const parsedCMD = ts.getParsedCommandLineOfConfigFile(
`tsconfig.lib.json`,
undefined,
ts.sys as any
);
const files = parsedCMD.fileNames;
const program = ts.createProgram(files, parsedCMD.options);
const checker = program.getTypeChecker();
const sourceFile = program.getSourceFile('group.ts');
ts.forEachChild(sourceFile, (node: ts.Node) => {
if (ts.isClassDeclaration(node)) {
node.members.forEach(member => {
if (ts.isPropertyDeclaration(member)) {
const type = checker.getTypeAtLocation(member.name);
console.log(type);
/**
* Output for element: HtmlButtonElement
*
* callSignatures: undefined
* checker: {getNodeCount: ƒ, getIdentifierCount: ƒ, getSymbolCount: ƒ, getTypeCount: ƒ,
* getRelationCacheSizes: ƒ, …}
* constructSignatures: undefined
* flags: 524288
* id: 74
* members: undefined
* numberIndexInfo: undefined
* objectFlags: 2
* properties: undefined
* stringIndexInfo: undefined
* symbol: SymbolObject {flags: 65, escapedName: "HTMLButtonElement", declarations: Array(2), * members: Map(20), parent: undefined, …}
* Was able resolve Symbols and Nodes for HtmlButtonElement
*
*/
/**
* Output for member1: Person
* checker: {getNodeCount: ƒ, getIdentifierCount: ƒ, getSymbolCount: ƒ, getTypeCount: ƒ,
* getRelationCacheSizes: ƒ, …}
* flags: 1
* id: 4
* intrinsicName: "error"
* objectFlags: 0
*
* Getting error when using checker.getTypeAtLocation
*/
}
});
}
});
I want to access members and jsDocComments for Person class at member1 location. I'm able to get all members or properties for HtmlButtonElement using checker.getTypeAtLocation but not for member1: Person. What am i missing?
You should check the diagnostics on the program (ts.getPreEmitDiagnostics(program)). You will find the following along with other errors:
error TS2304: Cannot find name 'Person'.
member1: Person;
~~~~~~
So after importing Person into that file...
import { Person } from "./person";
...you can do the following:
ts.forEachChild(groupFile, node => {
if (ts.isClassDeclaration(node)) {
for (const member of node.members) {
if (ts.isPropertyDeclaration(member) && member.name.getText(groupFile) === "member1") {
const personType = typeChecker.getTypeAtLocation(member.name);
console.log(typeChecker.typeToString(personType));
for (const property of personType.getProperties()) {
console.log(property.name);
}
}
}
}
});
Outputs:
Person
name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With