typescript - ts-morph ile bir nesne literalinin özelliklerini nasıl alırız
Ben ts-morph kullanarak böyle bir dosyayı ayrıştırıyorum
const a = {property1: 20, property2: 30}
Burada bahsedilen ObjectLiteralExpression'ı nasıl alacağımı bir türlü çözemez gibi görünüyorum
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");
Şimdiye kadar bunu kullanıyorum. Bir ifade döndüren başlatıcıyı alıyorum, ama nesne söz dizimi ifadesini almanın bir yolunu bulamıyorum.
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
Cevap #1
Görünüşe göre, bunu yapmanın doğru yolu bu. Değişkeni yanlış adlandırdım ve hata vermedi
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
Cevap #2
Bunu başlatıcıya ObjectLiteralExpression vererek çalıştırdım, şöyle:
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
