读取 TypeScript 文件时从父级 class 获取信息
Get information from parent class when reading TypeScript files
我正在使用 ts.createProgram
和 program.getSourceFile
成功阅读 TS classes。
但是,当我读取 class 节点以列出属性时,它不会考虑来自父 class 的属性。我可以从 node.heritageClauses
.
得到扩展 classes 的符号和名称
我怎样才能同时获得父 classes 的属性列表?
即:
// 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;
}
在这种情况下,您可以通过以下方式获取父级 class 的类型:
const refundClassDecl = ...;
const refundClassType = checker.getTypeAtLocation(refundClassDecl);
const modelClassType = checker.getBaseTypes(refundClassType)[0];
虽然这并不适用于所有情况,因为基类型可以用于一个接口、多个接口,并且还可以选择具有 class(例如 class MyClass extends Child implements SomeInterface, OtherInterface {}
),或者在如果它是混合(例如 class MyClass extends Mixin(Base) {}
),则某些情况可能是交集类型...因此您需要确保代码处理这些情况。
综上所述,您可能只想获取 Refund
class' 类型的属性:
const properties = refundClassType.getProperties();
console.log(properties.map(p => p.name)); // ["id", "foo"]
我正在使用 ts.createProgram
和 program.getSourceFile
成功阅读 TS classes。
但是,当我读取 class 节点以列出属性时,它不会考虑来自父 class 的属性。我可以从 node.heritageClauses
.
我怎样才能同时获得父 classes 的属性列表?
即:
// 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;
}
在这种情况下,您可以通过以下方式获取父级 class 的类型:
const refundClassDecl = ...;
const refundClassType = checker.getTypeAtLocation(refundClassDecl);
const modelClassType = checker.getBaseTypes(refundClassType)[0];
虽然这并不适用于所有情况,因为基类型可以用于一个接口、多个接口,并且还可以选择具有 class(例如 class MyClass extends Child implements SomeInterface, OtherInterface {}
),或者在如果它是混合(例如 class MyClass extends Mixin(Base) {}
),则某些情况可能是交集类型...因此您需要确保代码处理这些情况。
综上所述,您可能只想获取 Refund
class' 类型的属性:
const properties = refundClassType.getProperties();
console.log(properties.map(p => p.name)); // ["id", "foo"]