【问题标题】:Get information from parent class when reading TypeScript files读取 TypeScript 文件时从父类获取信息
【发布时间】:2021-03-24 08:59:07
【问题描述】:
我正在使用ts.createProgram 和program.getSourceFile 成功阅读TS 课程。
但是当我读取类节点以列出属性时,它不考虑父类的属性。我可以从node.heritageClauses 获取扩展类的符号和名称。
如何获取父类的属性列表?
即:
// I can traverse the Refund class and find the *id* property along with its decorator.
export class Refund extends Model {
@int({sys: 'codd'})
public id?: number;
}
// How can I get information from the parent class Model?
export class Model {
@bar()
public foo: string;
}
【问题讨论】:
标签:
typescript
abstract-syntax-tree
typescript-compiler-api
【解决方案1】:
在这种情况下,您可以通过以下方式获取父类的类型:
const refundClassDecl = ...;
const refundClassType = checker.getTypeAtLocation(refundClassDecl);
const modelClassType = checker.getBaseTypes(refundClassType)[0];
但这并不适用于所有场景,因为基类型可以是一个接口、多个接口,并且还可以有一个类(例如class MyClass extends Child implements SomeInterface, OtherInterface {}),或者在某些情况下可以是一个交集类型,如果它是一个 mixin(例如 class MyClass extends Mixin(Base) {})...所以您需要确保代码能够处理这些场景。
说了这么多,你可能只想获取Refund类'类型的属性:
const properties = refundClassType.getProperties();
console.log(properties.map(p => p.name)); // ["id", "foo"]