I wondering if it's possible to get the nodes items of the array by using some method of typescript compiler api?
In my code I pass NAMES array to names property and I can do it with different ways like so:
const NAMES = ['John', 'Jack'];
const LAST_NAMES = ['Herbert', 'Moore'];
const person = {
names: NAMES,
lastNames: LAST_NAMES
};
Or by spread operator:
const NAMES = ['John', 'Jack'];
const LAST_NAMES = ['Herbert', 'Moore'];
const person = {
names: [...NAMES],
lastNames: [...LAST_NAMES]
};
Or:
const NAMES = ['John', 'Jack'];
const LAST_NAMES = ['Herbert', 'Moore'];
const person = {
names: [...Object.values(NAMES)],
lastNames: [...Object.values(LAST_NAMES)]
};
Or:
const person = {
names: ['John', 'Jack'],
lastNames: ['Herbert', 'Moore']
};
In the end I don't care how user is writing the code, I just care about the items nodes in the array.
Is there some function/method can help me to resolve them from names property? because I don't want to write code that check for each cases.
const person = {
names */<-- I'm here, how do I get the nodes of the array? */ : [...NAMES],
lastNames: [...LAST_NAMES]
};
import {
Project,
SyntaxKind,
PropertyAssignment,
ts,
ClassDeclaration
} from "ts-morph";
console.clear();
const project = new Project({
skipAddingFilesFromTsConfig: true
});
const appSourceFile = project.createSourceFile(
"app.ts",
`
const NAMES = ['John', 'Jack'];
const LAST_NAMES = ['Herbert', 'Moore'];
const person = {
names: [...Object.values(NAMES)],
lastNames: [...Object.values(LAST_NAMES)]
};
`
);
const names = appSourceFile
.getDescendantsOfKind(SyntaxKind.Identifier)
.find((n) => n.getText() === "names");
const arrayLiteralExpression = (names.getParent() as PropertyAssignment).getInitializer();
console.log({ arrayLiteralExpression }); <--???