![](/img/trans.png)
[英]Get all possible exports from module by TypeScript API or ts-morph
[英]how to get an object literal properties with ts-morph
我正在使用 ts-morph 解析這樣的文件
const a = {property1: 20, property2: 30}
我似乎無法弄清楚如何獲得此處提到的 ObjectLiteralExpression
https://ts-morph.com/details/object-literal-expressions
const properties = objectLiteralExpression.getProperties();
// or
const property = objectLiteralExpression.getProperty("propertyAssignment");
// or
const spreadAssignment = objectLiteralExpression.getProperty(
p => p.getText() === "...spreadAssignment",
);
// or
const method = objectLiteralExpression.getPropertyOrThrow("method");
這是我目前使用的。 我正在獲取返回表達式的初始化程序,但我找不到獲取 object 文字表達式的方法
const project = new Project()
project.addSourceFileAtPath(filePath)
const sourceFile = project.getSourceFileOrThrow(filePath)
const dec = sourceFile.getVariableDeclarationOrThrow(
'a'
)
const objectLiteralExpression = dec.getInitializer() as ObjectLiteralExpression //
console.log(objectLiteralExpression.getProperties())//This returns blank
顯然,這是正確的做法。 我把變量命名錯了,它沒有拋出
const project = new Project()
project.addSourceFileAtPath(filePath)
const sourceFile = project.getSourceFileOrThrow(filePath)
const dec = sourceFile.getVariableDeclarationOrThrow(
'a'
)
const objectLiteralExpression = dec.getInitializer() as ObjectLiteralExpression //
console.log(objectLiteralExpression.getProperties())//This returns blank
我通過將ObjectLiteralExpression
提供給初始化程序來使其工作,如下所示:
const project = new Project()
project.addSourceFileAtPath(filePath)
const sourceFile = project.getSourceFileOrThrow(filePath)
const dec = sourceFile.getVariableDeclarationOrThrow(
'a'
)
const dev = template.getVariableDeclarationOrThrow('a')
const objectLiteralExpression = dec.getInitializerIfKindOrThrow(ObjectLiteralExpression)
console.log(objectLiteralExpression.getProperties()) // output here
它像這樣對我有用:
getInitializerIfKindOrThrow() accepts emum SyntaxKind
const project = new Project();
project.addSourceFileAtPath(filePath);
const sourceFile = project.getSourceFileOrThrow(filePath);
const dec = sourceFile.getVariableDeclarationOrThrow(
'a'
);
const objectLiteralExpression = dec.getInitializerIfKindOrThrow(ts.SyntaxKind.ObjectLiteralExpression);
console.log(objectLiteralExpression.getProperties()); // output here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.