Ts-morph: Question : Is there an option to add property value while adding property to class declaration

Created on 14 Aug 2018  路  7Comments  路  Source: dsherret/ts-morph

Am using the below api to add a property to class

classDeclaration.addProperty({
                    isStatic: false,
                    name: propertyName,
                    type: propertyType
                })

Am not able to specify value for the property. It will be nice if there is an option to provide value.
I want to achieve the below usecase

Class A {
   test = 'myTestString'
}
question

All 7 comments

The key you're looking for is called initializer.

    this.classDeclaration.addProperty({
      name: 'test',
      initializer: '"my test string"',
    })

Thanks @lazarljubenovic . How do we update an exisiting property ?

First get the prop declaration with getProperty or similar.

const propDeclaration = classDeclaration.getPropertyOrThrow('oldName')

Then use the method fill which accepts the same argument as ClassDeclaration#addProperty to change it.

propDeclaration.fill({
  name: 'newName',
})

Thanks a lot :-)

Thanks @lazarljubenovic for answering this!

@SanthoshHari912 alternatively use propDeclaration.setInitializer("newName").

propertyDecln.fill does not work

with 18.0 version of ts simple ast.

@kyyash .fill is now called .set({ initializer: "newName" }). For this scenario it's best to use .setInitializer("newName") though.

Read the breaking changes document for more info: https://github.com/dsherret/ts-simple-ast/blob/master/breaking-changes.md#fill-methods-are-now-set

Was this page helpful?
0 / 5 - 0 ratings

Related issues

allenhwkim picture allenhwkim  路  4Comments

donaldpipowitch picture donaldpipowitch  路  5Comments

gt3 picture gt3  路  4Comments

anurbol picture anurbol  路  3Comments

GrandSchtroumpf picture GrandSchtroumpf  路  4Comments