ts-morph

Initializers

Getting

For example, given the following code:

const add = function(a: number, b: number) {
  return a + b;
};

The initializer can be retrieved in any of these ways:

variableDeclaration.getInitializer(); // returns: Expression | undefined
variableDeclaration.getInitializerOrThrow(); // returns: Expression
variableDeclaration.getInitializerIfKind(SyntaxKind.FunctionExpression); // returns: Expression | undefined
variableDeclaration.getInitializerIfKindOrThrow(SyntaxKind.FunctionExpression); // returns: Expression

Removing

Use .removeInitializer() on the parent node. For example:

variableDeclaration.removeInitializer();

Setting

Use .setInitializer(...):

variableDeclaration.setInitializer("2 + 2");