ts-morph

Class Declarations

Class declarations can be retrieved from source files, namespaces, or function bodies:

const classes = sourceFile.getClasses();
const class1 = sourceFile.getClass("Class1");
const firstClassWithConstructor = sourceFile.getClass(c => c.getConstructors().length > 0);

Name

It's important to note that class declarations may not have a name. For example:

export default class {
    // etc...
}

For this reason, the methods like .getName() and .getNameNode() are nullable on ClassDeclaration.

Add/Insert

Add or insert classes to a source file, namespace, or function like declarations by calling addClass(), addClasses(), insertClass(), or insertClasses().

const classDeclaration = sourceFile.addClass({
    name: "ClassName"
});

Remove

Call .remove():

classDeclaration.remove();

Extends expression

Will return ExpressionWithTypeArguments | undefined:

const extendsExpression = classDeclaration.getExtends();

Set the extends expression:

classDeclaration.setExtends("BaseClass");

Remove it:

classDeclaration.removeExtends();

Implements expressions

Will return ExpressionWithTypeArguments[]:

const implementsExpressions = classDeclaration.getImplements();

Add or insert implements expressions:

classDeclaration.addImplements("Named");
classDeclaration.addImplements(["Named", "Aged"]);
classDeclaration.insertImplements(1, "Named");
classDeclaration.insertImplements(1, ["Named", "Aged"]);

Remove an expression:

classDeclaration.removeImplements(0); // index
classDeclaration.removeImplements(classDeclaration.getImplements()[0]); // node

Base Types

Get the base types:

const baseTypes = classDeclaration.getBaseTypes(); // returns: Type[]

This is useful to use if you don't know if the class could possibly extend a mixin or a class.

Base Class

Get the base class:

const baseClass = classDeclaration.getBaseClass(); // returns: ClassDeclaration | undefined

Note: This is not a useful method to use if the base could possibly be a mixin. If you expect mixins, then use .getBaseTypes().

Derived Classes

Will return all the class declarations that derive from the current class:

const derivedClasses = classDeclaration.getDerivedClasses();

Constructor

Constructors can be retreived via getConstructors. This returns all the constructors in an ambient context, but will only return the implementation constructor otherwise.

const constructors = classDeclaration.getConstructors();

Add or insert a constructor or constructors by calling addConstructor(), addConstructors(), insertConstructor(), or insertConstructors().

const ctor = classDeclaration.addConstructor({ /* options like parameters may go here */ });

Methods

Get instance methods:

const instanceMethods = classDeclaration.getInstanceMethods();
const myMethod = classDeclaration.getInstanceMethod("myMethod");
const firstMethodWith2Params = classDeclaration.getInstanceMethod(m => m.getParameters().length === 2);

Get the static methods:

const staticMethods = classDeclaration.getStaticMethods();
const myStaticMethod = classDeclaration.getStaticMethod("myMethod");
const firstStaticMethodWith2Params = classDeclaration.getStaticMethod(m => m.getParameters().length === 2);

Add/Insert

Add or insert methods by using insertMethods(), insertMethod, addMethod, or addMethods:

const method = classDeclaration.addMethod({ isStatic: true, name: "myMethod", returnType: "string" });

Remove

Call .remove():

method.remove();

Properties

Get the instance properties (includes parameter properties):

const instanceProperties = classDeclaration.getInstanceProperties();
const myProperty = classDeclaration.getInstanceProperty("myProperty");
const myStringProperty = classDeclaration.getInstanceProperty(p =>
    TypeGuards.isPropertyDeclaration(p) && p.getType().getText() === "string");

Get the static properties:

const staticProperties = classDeclaration.getStaticProperties();
const myStaticProperty = classDeclaration.getStaticProperty("myStaticProperty");
const myStaticStringProperty = classDeclaration.getStaticProperty(p =>
    TypeGuards.isPropertyDeclaration(p) && p.getType().getText() === "string");

Add/Insert

Add or insert properties by using insertProperties(), insertProperty, addProperty, or addProperties:

const property = classDeclaration.addProperty({ isStatic: true, name: "prop", type: "string" });

Add or insert get accessors by using insertGetAccessors(), insertGetAccessor, addGetAccessor, or addGetAccessors:

const getAccessor = classDeclaration.addGetAccessor({ name: "someNumber", returnType: "number", statements: ["return 5;"] });

Add or insert set accessors by using insertSetAccessors(), insertSetAccessor, addSetAccessor, or addSetAccessors:

const setAccessor = classDeclaration.addSetAccessor({ name: "someNumber", parameters: [{ name: "value", type: "number" }], statements: ["_someNumber = value;"] });

Remove

Call .remove():

propertyDeclaration.remove();

Get members

Get all the members regardless of whether static or instance:

const allMembers = classDeclaration.getMembers();

Get instance members including parameter properties:

const instanceMembers = classDeclaration.getInstanceMembers();

Get static members:

const staticMembers = classDeclaration.getStaticMembers();

Extracting an Interface

An interface declaration structure can be extracted from a class by calling classDeclaration.extractInterface(). For example:

// the passed in name is optional and defaults to the class name
const interfaceStructure = classDeclaration.extractInterface(`I${classDeclaration.getName()}`);

Alternatively the static interface declaration structure of a class can be extracted by calling:

const interfaceStructure = classDeclaration.extractStaticInterface(`${classDeclaration.getName()}Static`);

Abstract

Nodes on a class may be abstract.

Get if it's abstract:

method.isAbstract(); // returns: boolean

Get the abstract keyword:

method.getAbstractKeyword(); // returns: node | undefined

Set if abstract:

method.setIsAbstract(true);  // set as abstract
method.setIsAbstract(false); // set as not abstract

Constructors

Constructors implement common functions found on function like declarations, but also include a scope.

Methods

Explore the functionality available via auto-complete.

Properties

Explore the functionality available via auto-complete.

Get Accessors

If it exists, get the corresponding set accessor:

const setAccessor = getAccessor.getSetAccessor();

Set Accessors

If it exists, get the corresponding get accessor:

const getAccessor = setAccessor.getGetAccessor();