网站搜索

typescript - 如何使用 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");

到目前为止,我使用的是这个。我得到了返回一个表达式的初始化器,但我找不到获取对象字面量表达式的方法

    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

答案#1

显然,这是正确的做法。我给变量命名错了,但没有报错

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

答案#2

我通过将 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