'how to get an object literal properties with ts-morph
I am parsing a file like this using ts-morph
const a = {property1: 20, property2: 30}
I can't seem to figure out how to get an ObjectLiteralExpression mentioned here
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");
This is what I am using so far. I am getting the initializer which returns an expression, but I can't find a way to get the object literal expression
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
Solution 1:[1]
Apparently, this is the right way to do it. I named the variable wrong and it didn't throw
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
Solution 2:[2]
I got it working by giving ObjectLiteralExpression
to the initializer, like this:
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
Solution 3:[3]
It worked for me like this:
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | SoWhat |
Solution 2 | benjick |
Solution 3 | Dsklr |