### Setup and Build All Packages with Deno Source: https://github.com/dsherret/ts-morph/blob/latest/DEVELOPMENT.md Run this command in the root of the repository to install, set up, and build all packages for development. ```bash deno task setup ``` -------------------------------- ### Get All Source Files Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/getting-source-files.md Retrieve all source files within the project. No specific setup is required beyond having a Project instance. ```typescript const sourceFiles = project.getSourceFiles(); ``` -------------------------------- ### Install ts-morph with npm Source: https://github.com/dsherret/ts-morph/blob/latest/docs/index.md Install ts-morph as a development dependency using npm. ```bash npm install --save-dev ts-morph ``` -------------------------------- ### Get Structure, Remove Exports, Create New File Source: https://github.com/dsherret/ts-morph/blob/latest/docs/manipulation/performance.md This example demonstrates how to get a structure from an existing source file, modify it to remove exports, and then create a new file from the modified structure. It's useful for code generation or refactoring tasks where you want to create a new file based on an existing one with specific modifications. ```typescript import { forEachStructureChild, SourceFileStructure, StructureKind, Structures } from "ts-morph"; const project = new Project({ tsConfigFilePath: "tsconfig.json" }); const classesFile = project.getSourceFileOrThrow("declarations.ts"); const classesFileStructure = classesFile.getStructure(); removeExports(classesFileStructure); project.createSourceFile("private.ts", classesFileStructure); function removeExports(structure: Structures) { forEachStructureChild(structure, removeExports); if (Structure.isExportable(structure)) structure.isExported = false; } ``` -------------------------------- ### Install ts-morph with Deno JSR Source: https://github.com/dsherret/ts-morph/blob/latest/docs/index.md Add ts-morph to your Deno project using JSR for installation. ```bash deno add ts-morph@jsr:@ts-morph/ts-morph ``` -------------------------------- ### Example Class Declaration Source: https://github.com/dsherret/ts-morph/blob/latest/docs/manipulation/structures.md An example of a TypeScript class declaration. ```typescript export class MyClass { myProp = 5; } ``` -------------------------------- ### Module and Namespace Declaration Syntax Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/modules.md Examples of different syntaxes for module and namespace declarations. ```typescript namespace MyNamespace { } module MyModule { } declare module "some-module" { } declare module "other-module"; ``` -------------------------------- ### Example Class Structure Object Source: https://github.com/dsherret/ts-morph/blob/latest/docs/manipulation/structures.md A JavaScript object representing the structure of the example class declaration. ```javascript { isAbstract: false, isExported: true, name: "MyClass", typeParameters: [], constructors: [], properties: [{ name: "myProp", initializer: "5", type: undefined, isReadonly: false, isStatic: false }], methods: [] } ``` -------------------------------- ### Getting Initializers Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/initializers.md Demonstrates how to retrieve the initializer expression of a variable declaration. ```APIDOC ## Getting Initializers ### Description Retrieves the initializer expression of a variable declaration. ### Method `getInitializer()` ### Endpoint N/A (Method on a ts-morph node) ### Parameters None ### Request Example ```ts // Assuming 'variableDeclaration' is a VariableDeclaration node const initializer = variableDeclaration.getInitializer(); ``` ### Response #### Success Response - **initializer** (Expression | undefined) - The initializer expression, or undefined if none exists. ### Method `getInitializerOrThrow()` ### Endpoint N/A (Method on a ts-morph node) ### Parameters None ### Request Example ```ts // Assuming 'variableDeclaration' is a VariableDeclaration node const initializer = variableDeclaration.getInitializerOrThrow(); ``` ### Response #### Success Response - **initializer** (Expression) - The initializer expression. ### Method `getInitializerIfKind(kind: SyntaxKind)` ### Endpoint N/A (Method on a ts-morph node) ### Parameters - **kind** (SyntaxKind) - The expected kind of the initializer expression. ### Request Example ```ts // Assuming 'variableDeclaration' is a VariableDeclaration node const functionExpression = variableDeclaration.getInitializerIfKind(SyntaxKind.FunctionExpression); ``` ### Response #### Success Response - **initializer** (Expression | undefined) - The initializer expression if it matches the kind, otherwise undefined. ### Method `getInitializerIfKindOrThrow(kind: SyntaxKind)` ### Endpoint N/A (Method on a ts-morph node) ### Parameters - **kind** (SyntaxKind) - The expected kind of the initializer expression. ### Request Example ```ts // Assuming 'variableDeclaration' is a VariableDeclaration node const functionExpression = variableDeclaration.getInitializerIfKindOrThrow(SyntaxKind.FunctionExpression); ``` ### Response #### Success Response - **initializer** (Expression) - The initializer expression if it matches the kind. ``` -------------------------------- ### Get Implementations Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/interfaces.md Retrieve the implementations of an interface, similar to the 'go to implementation' IDE command. ```typescript const implementations = interfaceDeclaration.getImplementations(); ``` -------------------------------- ### BindingElement Example in ts-morph Source: https://github.com/dsherret/ts-morph/blob/latest/packages/ts-morph/breaking-changes.md Shows how to correctly retrieve a BindingElement from a variable declaration. This example demonstrates accessing destructured elements and their names. ```typescript const statement = sourceFile.getVariableStatements()[0]; const declaration = statement.getDeclarations(); const name = declaration.getNameNode(); if (TypeGuards.isBindingElement(name)) console.log(name.getElements().map(e => e.getName())); // outputs: ["a", "b"] ``` -------------------------------- ### Retrieve Directories from Project Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/directories.md Get root directories, all directories, or a specific directory by path from the project object. ```typescript project.getRootDirectories(); // gets directories without a parent project.getDirectories(); // gets all the directories project.getDirectory("path/to/directory"); project.getDirectoryOrThrow("path/to/directory"); ``` -------------------------------- ### Manage Source Files within a Directory Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/directories.md Retrieve source files, get a specific source file by name, add a source file at a path, or get all descendant source files. Also includes methods to create new source files with content or structures. ```typescript const sourceFiles = directory.getSourceFiles(); const sourceFile = directory.getSourceFile("someFile.ts"); // or getSourceFileOrThrow const indexFile = directory.addSourceFileAtPath("index.ts"); // or addSourceFileAtPathIfExists const descendantSourceFiles = directory.getDescendantSourceFiles(); directory.createSourceFile("someFile.ts"); directory.createSourceFile("someFile2.ts", "// some text"); directory.createSourceFile("someFile3.ts", writer => writer.writeLine("// some text")); directory.createSourceFile("someFile4.ts", { statements: [{ kind: StructureKind.Enum, name: "MyEnum" }] }); ``` -------------------------------- ### Example Identifier Usage Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/identifiers.md Demonstrates a basic variable declaration and usage, where both the declaration and the usage are identifiers. ```typescript const identifier = 5; console.log(identifier); ``` -------------------------------- ### Get Base Type of Literal Type Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/types.md Obtain the base type from a literal type. Example setup requires a `numberLiteralType` variable. ```typescript const numberType = numberLiteralType.getBaseTypeOfLiteralType(); ``` -------------------------------- ### Get Diagnostic Start Position Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/diagnostics.md Get the starting character position of the diagnostic within its source file. This is a numerical offset. ```typescript const start = diagnostic.getStart(); // returns: number ``` -------------------------------- ### Initialize Project with Custom File System Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/file-system.md Creates a new Project instance by providing a custom implementation of the FileSystemHost interface. ```typescript import { FileSystemHost, Project } from "ts-morph"; class MyCustomFileSystem implements FileSystemHost { // implement it } const fs = new MyCustomFileSystem(); const project = new Project({ fileSystem: fs }); ``` -------------------------------- ### Create and Use Project Source: https://github.com/dsherret/ts-morph/blob/latest/packages/bootstrap/readme.md Initializes a new project and creates source files. Accesses the program, type checker, and language service. Use `createProjectSync` for synchronous operations. ```typescript import { createProject, ts } from "@ts-morph/bootstrap"; const project = await createProject(); // or createProjectSync // these are typed as ts.SourceFile const myClassFile = project.createSourceFile( "MyClass.ts", "export class MyClass { prop: string; }", ); const mainFile = project.createSourceFile( "main.ts", "import { MyClass } from './MyClass'", ); // ts.Program const program = project.createProgram(); // ts.TypeChecker const typeChecker = program.getTypeChecker(); // ts.LanguageService const languageService = project.getLanguageService(); // ts.ModuleResolutionHost const moduleResolutionHost = project.getModuleResolutionHost(); ``` -------------------------------- ### Global Namespace Declaration Syntax Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/modules.md Example of a global namespace declaration within a module. ```typescript declare module "my-library" { // this is a global namespace declaration global { const foo: string; } } ``` -------------------------------- ### Resolving Signature of Call-Like Expressions Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/type-checker.md Provides an example of how to use the Type Checker to get the resolved signature of a call-like expression. ```APIDOC ## Signature Resolution ### Description Get the resolved signature of a call-like expression node (e.g., a call expression) using the `getResolvedSignature` method. ### Method ```ts const resolvedSignature = typeChecker.getResolvedSignature(callLikeExpression); ``` ### Endpoint N/A (This is a method call within the ts-morph library) ### Parameters - **callLikeExpression** (CallExpression | NewExpression | TaggedTemplateExpression | Decorator) - The node for which to resolve the signature. ### Request Example ```ts // Assuming 'typeChecker' is an initialized ts-morph TypeChecker object // and 'callLikeExpression' is a valid ts-morph node representing a call-like expression const resolvedSignature = typeChecker.getResolvedSignature(callLikeExpression); ``` ### Response - **resolvedSignature** (ts.Signature | undefined) - The resolved signature of the expression, or undefined if not found. ``` -------------------------------- ### Setup Project with tsconfig.json Source: https://github.com/dsherret/ts-morph/blob/latest/packages/bootstrap/readme.md Creates a project instance, optionally specifying the path to a tsconfig.json file. Compiler options from the tsconfig.json will be used. Use `createProjectSync` for synchronous operations. ```typescript const project = await createProject({ tsConfigFilePath: "tsconfig.json" }); ``` ```typescript const project = createProjectSync({ tsConfigFilePath: "tsconfig.json" }); ``` -------------------------------- ### Working with Export Declarations Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/exports.md Detailed information on how to get, check, and manipulate export declarations. ```APIDOC ## Export Declarations ### Description Export declarations represent constructs like `export { ... }` or `export * from ...`. This section details how to interact with them. ### Methods - `getExportDeclarations(): ExportDeclaration[]` - `getExportDeclaration(condition: (declaration: ExportDeclaration) => boolean): ExportDeclaration | undefined` - `getExportDeclaration(moduleSpecifier: string): ExportDeclaration | undefined` - `hasNamedExports(): boolean` - `isNamespaceExport(): boolean` - `getModuleSpecifier(): StringLiteral | undefined` - `getModuleSpecifierValue(): string | undefined` - `setModuleSpecifier(value: string | SourceFile): void` - `removeModuleSpecifier(): void` - `hasModuleSpecifier(): boolean` - `isModuleSpecifierRelative(): boolean` - `getModuleSpecifierSourceFile(): SourceFile | undefined` ### Example ```ts // Get all export declarations const exportDeclarations = sourceFile.getExportDeclarations(); // Get the first export declaration that has named exports const exportDeclaration = sourceFile.getExportDeclaration(d => d.hasNamedExports()); // Get an export declaration by its module specifier const exportDecForModule = sourceFile.getExportDeclaration("./some-file"); // Check if it has named exports exportDeclaration.hasNamedExports(); // Check if it's a namespace export exportDeclaration.isNamespaceExport(); // Get and set the module specifier exportDeclaration.getModuleSpecifier(); // returns: StringLiteral | undefined exportDeclaration.getModuleSpecifierValue(); // returns: string | undefined exportDeclaration.setModuleSpecifier("./new-file"); exportDeclaration.setModuleSpecifier(sourceFile); exportDeclaration.removeModuleSpecifier(); exportDeclaration.hasModuleSpecifier(); // returns: boolean exportDeclaration.isModuleSpecifierRelative(); // if the module specifier starts with ./ or ../ exportDeclaration.getModuleSpecifierSourceFile(); // returns: SourceFile | undefined ``` ``` -------------------------------- ### Instantiate Project with Compiler Options Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/index.md Configure the project by providing compiler options during instantiation. This allows you to set targets like ES3. ```typescript import { Project, ScriptTarget } from "ts-morph"; const project = new Project({ compilerOptions: { target: ScriptTarget.ES3, }, }); ``` -------------------------------- ### Get Non-Nullable Type Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/types.md Obtain the non-nullable version of a type, removing `null` or `undefined`. For example, `string | undefined` becomes `string`. ```typescript const nonNullableType = type.getNonNullableType(); ``` -------------------------------- ### Setup ts-morph Project Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/example.md Initializes a ts-morph Project and adds all TypeScript files from the current directory and its subdirectories. ```typescript import { Project } from "ts-morph"; const project = new Project(); project.addSourceFilesAtPaths("**/*.ts"); ``` -------------------------------- ### Initialize Project with In-Memory File System Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/file-system.md Creates a new Project instance configured to use an in-memory file system. This is useful for testing purposes. ```typescript import { Project } from "ts-morph"; const project = new Project({ useInMemoryFileSystem: true }); const fs = project.getFileSystem(); const sourceFile = project.createSourceFile("file.ts", "console.log(5);"); sourceFile.saveSync(); console.log(fs.readFileSync("file.ts")); // outputs: "console.log(5);" ``` -------------------------------- ### Get All Ambient Modules Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/ambient-modules.md Retrieves all ambient modules resolved by the compiler, such as those found in `@types` or `node_modules`. No setup is required beyond having a ts-morph project instance. ```typescript const ambientModules = project.getAmbientModules(); ``` -------------------------------- ### Get Named Exports from Export Declaration Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/exports.md Retrieve all named exports associated with an export declaration. No specific setup is required beyond having an `ExportDeclaration` node. ```typescript const namedExports = exportDeclaration.getNamedExports(); ``` -------------------------------- ### Get Type Parameters from Node Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/type-parameters.md Retrieve all type parameters associated with a node, such as a class declaration. No specific setup is required beyond having a ts-morph node. ```typescript const typeParameters = classDeclaration.getTypeParameters(); ``` -------------------------------- ### Build Packages with Deno Source: https://github.com/dsherret/ts-morph/blob/latest/DEVELOPMENT.md Builds the packages. This command can be run in the root directory or on a per-package basis. ```bash deno task build ``` -------------------------------- ### Instantiate Project with Custom Module Resolution Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/index.md Implement custom module resolution logic by providing a `resolutionHost` factory function. This example demonstrates Deno-style module resolution. ```typescript import { Project, ts } from "ts-morph"; // this is deno style module resolution (ex. `import { MyClass } from "./MyClass.ts"`) const project = new Project({ resolutionHost: (moduleResolutionHost, getCompilerOptions) => { return { resolveModuleNames: (moduleNames, containingFile) => { const compilerOptions = getCompilerOptions(); const resolvedModules: ts.ResolvedModule[] = []; for (const moduleName of moduleNames.map(removeTsExtension)) { const result = ts.resolveModuleName(moduleName, containingFile, compilerOptions, moduleResolutionHost); if (result.resolvedModule) resolvedModules.push(result.resolvedModule); } return resolvedModules; }, }; function removeTsExtension(moduleName: string) { if (moduleName.slice(-3).toLowerCase() === ".ts") return moduleName.slice(0, -3); return moduleName; } }, }); ``` -------------------------------- ### Format Code with Deno Source: https://github.com/dsherret/ts-morph/blob/latest/DEVELOPMENT.md Formats the code according to project standards. Run this command from the root directory. ```bash deno task format ``` -------------------------------- ### Add Get and Set Accessors Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/object-literal-expressions.md Adds get and set accessors to an object literal. You can specify the name, return type (for get), parameters (for set), and statements for the accessor. ```typescript const getAccessor = objectLiteralExpression.addGetAccessor({ name: "someNumber", returnType: "number", statements: ["return someNumber;"], }); ``` ```typescript const setAccessor = objectLiteralExpression.addSetAccessor({ name: "someNumber", parameters: [{ name: "value", type: "number" }], statements: ["someNumber = value;"], }); ``` -------------------------------- ### Getting the Async Keyword Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/async.md Retrieve the async keyword token if it exists on a node. ```APIDOC ### `async` keyword ### Description Get the `async` keyword if it exists. ### Method `getAsyncKeyword()` ### Endpoint N/A (Method on a Node object) ### Parameters None ### Request Example ```ts functionDeclaration.getAsyncKeyword(); ``` ### Response #### Success Response (AsyncKeyword | undefined) - The `AsyncKeyword` token if it exists. - `undefined` if the node does not have an async keyword. #### Response Example ```json // Example if async keyword exists { "kind": 105 // Example kind for AsyncKeyword } // Example if async keyword does not exist undefined ``` ``` -------------------------------- ### File System Configuration Source: https://github.com/dsherret/ts-morph/blob/latest/packages/bootstrap/readme.md Configures the project to use either a real file system, an in-memory file system, or a custom file system implementation. Use `createProjectSync` for synchronous operations. ```typescript // will use a real file system const project = await createProject(); ``` ```typescript // in memory file system const project2 = await createProject({ useInMemoryFileSystem: true }); ``` ```typescript // custom file system const fileSystem: FileSystemHost = { ...etc... }; const project = await createProject({ fileSystem }); ``` ```typescript project.fileSystem.writeFileSync("MyClass.ts", "class MyClass {}"); ``` -------------------------------- ### Project Constructor with Custom File System Host Source: https://github.com/dsherret/ts-morph/blob/latest/packages/ts-morph/breaking-changes.md The custom file system host is now passed as an option to the `Project` constructor instead of as a separate argument. ```typescript const project = new Project({}, fileSystem); ``` ```typescript const project = new Project({ fileSystem }); ``` -------------------------------- ### Checking and Getting Export Keywords Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/exports.md Methods to check for the presence of 'export' and 'default' keywords, and to retrieve them. ```APIDOC ## Checking and Getting Export Keywords ### Description Use the `has` methods to check for the `export` and `default` keywords, and the `get` methods to retrieve them. ### Methods - `hasExportKeyword(): boolean` - `hasDefaultKeyword(): boolean` - `getExportKeyword()` - `getDefaultKeyword()` ### Example ```ts functionDeclaration.hasExportKeyword(); // returns: boolean functionDeclaration.hasDefaultKeyword(); // returns: boolean functionDeclaration.getExportKeyword(); functionDeclaration.getDefaultKeyword(); ``` ``` -------------------------------- ### Copying Directories Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/directories.md Demonstrates how to copy a directory to a new location, with options for overwriting, specifying absolute paths, and copying to a specific directory. It also explains how to exclude untracked files during the copy process. ```APIDOC ## Copying Directories ### Description Copies the directory to a new directory. ### Method `directory.copy(path: string | Directory, options?: { overwrite?: boolean, includeUntrackedFiles?: boolean }): void` `directory.copyToDirectory(path: string | Directory): void` ### Endpoint N/A (Method calls on a Directory object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts // ex. copies C:\MyProject\dir to C:\MyProject\newDir directory.copy("../newDir"); // allows overwriting (otherwise it will throw) directory.copy("../nextDir", { overwrite: true }); // or specify an absolute path directory.copy("C:\\test"); // or specify the directory to copy to directory.copyToDirectory("some/directory"); directory.copyToDirectory(otherDir); // Not including untracked files directory.copy("../finalDir", { includeUntrackedFiles: false }); ``` ### Response #### Success Response (200) None (operations are queued) #### Response Example None ``` -------------------------------- ### Generated Source File from Structure Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/adding-source-files.md This is the resulting code generated from the structure object in the previous example. ```typescript enum MyEnum { member, } class MyClass { } ``` -------------------------------- ### Create a ts-morph Project Instance Source: https://context7.com/dsherret/ts-morph/llms.txt Instantiate the Project class, the main entry point for ts-morph. Options include basic instantiation, with compiler options, or from a tsconfig.json file. ```typescript import { Project, ScriptTarget } from "ts-morph"; // Basic instantiation const project = new Project(); // With compiler options const projectWithOptions = new Project({ compilerOptions: { target: ScriptTarget.ES2020, strict: true, }, }); // From tsconfig.json (automatically adds source files) const projectFromTsConfig = new Project({ tsConfigFilePath: "path/to/tsconfig.json", }); // From tsconfig.json without auto-adding files const projectManual = new Project({ tsConfigFilePath: "path/to/tsconfig.json", skipAddingFilesFromTsConfig: true, }); ``` -------------------------------- ### Get Index Signatures Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/interfaces.md Retrieve index signatures from an interface declaration. Can get all or the first matching a condition. ```typescript const indexSignatures = interfaceDeclaration.getIndexSignatures(); const indexSignature = interfaceDeclaration.getIndexSignature(s => s.getKeyName() === "keyName"); ``` -------------------------------- ### Get Call Signatures Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/interfaces.md Retrieve call signatures from an interface declaration. Can get all or the first matching a condition. ```typescript const callSignatures = interfaceDeclaration.getCallSignatures(); const callSignature = interfaceDeclaration.getCallSignature(c => c.getParameters().length > 2); ``` -------------------------------- ### Instantiate Project with Custom Lib Folder Path Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/index.md Specify a custom `libFolderPath` to load TypeScript lib files from the file system instead of using the default in-memory path. ```typescript const project = new Project({ libFolderPath: "./node_modules/typescript/lib", }); ``` -------------------------------- ### Get Construct Signatures Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/interfaces.md Retrieve construct signatures from an interface declaration. Can get all or the first matching a condition. ```typescript const constructSignatures = interfaceDeclaration.getConstructSignatures(); const constructSignature = interfaceDeclaration.getConstructSignature(c => c.getParameters().length > 2); ``` -------------------------------- ### Instantiate Project with tsconfig.json and Skip Adding Files Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/index.md When specifying a `tsconfig.json` path, set `skipAddingFilesFromTsConfig` to `true` if you do not want to automatically add source files from the tsconfig. ```typescript const project = new Project({ tsConfigFilePath: "path/to/tsconfig.json", skipAddingFilesFromTsConfig: true, }); ``` -------------------------------- ### Get Properties Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/interfaces.md Retrieve properties from an interface declaration. Can get all, a specific property by name, or the first matching a condition. ```typescript const properties = interfaceDeclaration.getProperties(); const myProperty = interfaceDeclaration.getProperty("myProperty"); const firstStringProperty = interfaceDeclaration.getProperty(p => p.getType().getText() === "string"); ``` -------------------------------- ### Instantiate Project with tsconfig.json Path Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/index.md Specify the path to your `tsconfig.json` file when creating a new project. This automatically adds associated source files. ```typescript const project = new Project({ tsConfigFilePath: "path/to/tsconfig.json", }); ``` -------------------------------- ### Example Code with Only Comments Source: https://github.com/dsherret/ts-morph/blob/latest/rfcs/RFC-0001 - Inserting Into Statements Handling Comments.md Demonstrates a source file containing only comments, which should be returned when calling a method like '#getStatementsWithComments()'. ```typescript // comment 1 /* comment 2 */ ``` -------------------------------- ### Get Instance Class Members Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/classes.md Use `getInstanceMembers()` to get only the instance members of a class, including parameter properties. ```typescript const instanceMembers = classDeclaration.getInstanceMembers(); ``` -------------------------------- ### Get Get Accessor from Set Accessor Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/classes.md If a setter exists, use `getGetAccessor()` on the setter node to retrieve its corresponding getter. ```typescript const getAccessor = setAccessor.getGetAccessor(); ``` -------------------------------- ### Example: Rename Default Import Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/imports.md Demonstrates renaming a default import and its usages. The code shows the transformation from the original to the refactored state. ```typescript const importDeclaration = sourceFile.getImportDeclarations()[0]; importDeclaration.renameDefaultImport("NewName"); ``` -------------------------------- ### Get Set Accessor from Get Accessor Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/classes.md If a getter exists, use `getSetAccessor()` on the getter node to retrieve its corresponding setter. ```typescript const setAccessor = getAccessor.getSetAccessor(); ``` -------------------------------- ### Get Type Text Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/types.md Get the string representation of a type using `.getText()`. Provide an enclosing node for better accuracy. ```typescript const text = type.getText(); ``` ```typescript const text = type.getText(parameter); ``` -------------------------------- ### In-Memory File System with All Lib Files Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/file-system.md Configures the Project with an in-memory file system and specifies 'lib.esnext.full.d.ts' to include all available lib files. ```typescript const project = new Project({ useInMemoryFileSystem: true, compilerOptions: { lib: ["lib.esnext.full.d.ts"], }, }); ``` -------------------------------- ### Get All Import Declarations Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/imports.md Retrieve all import declarations from a source file. Use this to iterate through all imports. ```typescript const imports = sourceFile.getImportDeclarations(); ``` -------------------------------- ### Get Method Signatures Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/interfaces.md Retrieve method signatures from an interface declaration. Can get all, a specific method by name, or the first matching a condition. ```typescript const methodSignatures = interfaceDeclaration.getMethods(); const myMethod = interfaceDeclaration.getMethod("myMethod"); const firstMethodWith4Params = interfaceDeclaration.getMethod(m => m.getParameters().length === 4); ``` -------------------------------- ### Create Directory in Project Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/directories.md Create a new directory at a specified path within the project. ```typescript const directory = project.createDirectory("path/to/dir"); ``` -------------------------------- ### Get Named Import Name Node Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/imports.md Retrieve the Identifier node for the name of a named import. Use this to get or manipulate the name itself. ```typescript namedImport.getNameNode(); ``` -------------------------------- ### Copying Directories Immediately Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/directories.md Provides methods to copy a directory immediately to the file system, bypassing the queued operation system. ```APIDOC ## Copying Directories Immediately ### Description Copies a directory immediately to the file system. ### Method `await directory.copyImmediately(path: string | Directory): Promise` `directory.copyImmediatelySync(path: string | Directory): void` ### Endpoint N/A (Method calls on a Directory object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts await directory.copyImmediately("../otherDir"); // or directory.copyImmediatelySync("../otherDir2"); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Deleting Directories Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/directories.md Explains how to delete a directory from the project object and queue it for file system deletion. It also covers immediate deletion. ```APIDOC ## Deleting Directories ### Description Removes the directory object and all its descendant source files and directories from the main `project` object and queues it up for deletion to the file system. ### Method `directory.delete(): void` `await directory.deleteImmediately(): Promise` `directory.deleteImmediatelySync(): void` ### Endpoint N/A (Method calls on a Directory object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts directory.delete(); // Deleting immediately await directory.deleteImmediately(); // or directory.deleteImmediatelySync(); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get Module Specifier Value Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/imports.md Get the string value of the module specifier. For `import settings from "./settings";`, this returns `./settings`. ```typescript const moduleSpecifierValue = importDeclaration.getModuleSpecifierValue(); ``` -------------------------------- ### Get Instance Methods Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/classes.md Retrieve all instance methods declared in a class. You can get all methods, a specific method by name, or the first method matching a condition. ```typescript const instanceMethods = classDeclaration.getInstanceMethods(); const myMethod = classDeclaration.getInstanceMethod("myMethod"); const firstMethodWith2Params = classDeclaration.getInstanceMethod(m => m.getParameters().length === 2); ``` -------------------------------- ### Create Source File from String Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/adding-source-files.md Create a new source file by providing the file content as a string. Ensure correct newline characters are used for multi-line content. ```typescript const fileText = "enum MyEnum {\n}\n"; const sourceFile = project.createSourceFile("path/to/myNewFile.ts", fileText); ``` -------------------------------- ### Get Export Declarations Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/exports.md Retrieve export declarations from a source file using `getExportDeclarations()`. You can get the first matching declaration with a condition or by module specifier. ```typescript const exportDeclarations = sourceFile.getExportDeclarations(); // or to get the first one that matches a condition const exportDeclaration = sourceFile.getExportDeclaration(d => d.hasNamedExports()); const exportDecForModule = sourceFile.getExportDeclaration("module-specifier-text"); ``` -------------------------------- ### Get Interface Declarations Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/interfaces.md Retrieve interface declarations from a source file. Can get all interfaces, a specific interface by name, or the first interface matching a condition. ```typescript const interfaces = sourceFile.getInterfaces(); const interface1 = sourceFile.getInterface("Interface1"); const firstInterfaceWith5Properties = sourceFile.getInterface(i => i.getProperties().length === 5); ``` -------------------------------- ### Configure Lib Files for In-Memory File System Source: https://github.com/dsherret/ts-morph/blob/latest/packages/ts-morph/breaking-changes.md Shows how to configure the `lib` compiler option when using an in-memory file system to ensure types like `Set` are available. This is necessary because the default target (ES5) does not implicitly include ES2015+ lib files. ```typescript const project = new Project({ useInMemoryFileSystem: true, compilerOptions: { lib: ["lib.es2015.d.ts"], }, }); ``` -------------------------------- ### Get Function Declarations Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/functions.md Retrieve function declarations from a source file. You can get all functions, a specific function by name, or the first function matching a condition. ```typescript const functions = sourceFile.getFunctions(); const function1 = sourceFile.getFunction("Function1"); const firstFunctionWithChildFunction = sourceFile.getFunction(f => f.getFunctions().length > 0); ``` -------------------------------- ### Example Code with Comments Source: https://github.com/dsherret/ts-morph/blob/latest/rfcs/RFC-0001 - Inserting Into Statements Handling Comments.md Illustrates a code snippet with various types of comments (single-line, multi-line, trailing) preceding a variable declaration. ```typescript // comment 1 /* comment 2 */ /* comment 3 */ const t = 4; // comment 4 const u = 5; ``` -------------------------------- ### Run Tests Recursively with Deno Source: https://github.com/dsherret/ts-morph/blob/latest/DEVELOPMENT.md Executes tests for all packages. This command can be run in the root directory or on a per-package basis. ```bash deno task --recursive test ``` -------------------------------- ### Get Class Declarations Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/classes.md Retrieve class declarations from a source file. You can get all classes, a specific class by name, or the first class matching a condition. ```typescript const classes = sourceFile.getClasses(); const class1 = sourceFile.getClass("Class1"); const firstClassWithConstructor = sourceFile.getClass(c => c.getConstructors().length > 0); ``` -------------------------------- ### Get Instance Properties Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/classes.md Retrieve instance properties, including parameter properties. You can get all properties, a specific property by name, or the first property matching a condition. ```typescript const instanceProperties = classDeclaration.getInstanceProperties(); const myProperty = classDeclaration.getInstanceProperty("myProperty"); const myStringProperty = classDeclaration.getInstanceProperty(p => Node.isPropertyDeclaration(p) && p.getType().getText() === "string"); ``` -------------------------------- ### Example with Multiple Comments on Same Line Source: https://github.com/dsherret/ts-morph/blob/latest/rfcs/RFC-0001 - Inserting Into Statements Handling Comments.md Shows an edge case with multiple comments on the same line, illustrating which comments are considered leading and which are trailing. ```typescript /* comment 1 */ // comment 2 /* comment 3 */ /* comment 4 */ // comment 5 ``` -------------------------------- ### Add Source Files by Globs or Paths Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/adding-source-files.md Add multiple source files to the project using file globs or an array of file paths. ```typescript project.addSourceFilesAtPaths("folder/**/*{.d.ts,.ts}"); ``` ```typescript project.addSourceFilesAtPaths(["folder/file.ts", "folder/otherFile.ts"]); ``` ```typescript project.addSourceFilesAtPaths(["**/*.ts", "!**/*.d.ts"]); ``` -------------------------------- ### Get Properties of an Object Literal Expression Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/object-literal-expressions.md Retrieves properties from an object literal expression. You can get all properties, a specific property by name, or a property using a predicate function. ```typescript const properties = objectLiteralExpression.getProperties(); ``` ```typescript const property = objectLiteralExpression.getProperty("propertyAssignment"); ``` ```typescript const spreadAssignment = objectLiteralExpression.getProperty( p => p.getText() === "...spreadAssignment", ); ``` ```typescript const method = objectLiteralExpression.getPropertyOrThrow("method"); ``` -------------------------------- ### Compiler Options Configuration Source: https://github.com/dsherret/ts-morph/blob/latest/packages/bootstrap/readme.md Creates a project instance and overrides or sets specific TypeScript compiler options. Use `createProjectSync` for synchronous operations. ```typescript const project = await createProject({ compilerOptions: { target: ts.ScriptTarget.ES3, }, }); ``` -------------------------------- ### Get Static Properties Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/classes.md Retrieve static properties declared in a class. You can get all static properties, a specific static property by name, or the first static property matching a condition. ```typescript const staticProperties = classDeclaration.getStaticProperties(); const myStaticProperty = classDeclaration.getStaticProperty("myStaticProperty"); const myStaticStringProperty = classDeclaration.getStaticProperty(p => Node.isPropertyDeclaration(p) && p.getType().getText() === "string"); ``` -------------------------------- ### Get Static Methods Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/classes.md Retrieve all static methods declared in a class. You can get all static methods, a specific static method by name, or the first static method matching a condition. ```typescript const staticMethods = classDeclaration.getStaticMethods(); const myStaticMethod = classDeclaration.getStaticMethod("myMethod"); const firstStaticMethodWith2Params = classDeclaration.getStaticMethod(m => m.getParameters().length === 2); ``` -------------------------------- ### Get Function Expression from Variable Declaration Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/functions.md Retrieve a function expression that is assigned as the initializer of a variable declaration. This involves getting the variable declaration and then its initializer, ensuring it's a function expression. ```typescript const add = function(a: number, b: number) { return a + b; }; const functionExpression = sourceFile.getVariableDeclarationOrThrow("add") .getInitializerIfKindOrThrow(SyntaxKind.FunctionExpression); ``` -------------------------------- ### Initialize Project with Partial Manipulation Settings Source: https://github.com/dsherret/ts-morph/blob/latest/docs/manipulation/settings.md Provide only a subset of manipulation settings when creating a ts-morph Project. The remaining settings will use their default values. ```typescript const project = new Project({ manipulationSettings: { indentationText: IndentationText.TwoSpaces }, }); ``` -------------------------------- ### Emit Directory with Output Options Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/directories.md Specify output directories for JavaScript and declaration files during the emit process. ```typescript directory.emit({ outDir: "out", declarationDir: "declarations", }); ``` -------------------------------- ### Manipulate Property Type and Get Text Source: https://github.com/dsherret/ts-morph/blob/latest/docs/manipulation/performance.md Demonstrates how ts-morph tracks nodes across manipulations. After changing a property's type, you can immediately get its updated text without needing to re-navigate the AST. ```typescript // sourcefile contains: interface Person { name: string; } const personInterface = sourceFile.getInterfaceOrThrow("Person"); const nameProperty = personInterface.getPropertyOrThrow("name"); nameProperty.setType("number"); nameProperty.getText(); // "name: number;" ``` -------------------------------- ### Signature Parameters Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/signatures.md Get the parameters of a signature. ```APIDOC ## Signature Parameters ### Description Retrieves the parameters of a signature. ### Method ```ts signature.getParameters() ``` ### Returns `Symbol[]` - An array of symbol objects representing the parameters. ``` -------------------------------- ### Getting All Modifiers Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/modifiers.md Retrieve all modifiers associated with a node. ```APIDOC ## Getting all modifiers ### Description Retrieves all modifiers associated with a node. ### Method `getModifiers()` ### Endpoint N/A (This is a library function, not an API endpoint) ### Parameters None ### Request Example ```ts functionDeclaration.getModifiers(); ``` ### Response #### Success Response (Array of Modifiers) - Returns an array of modifier nodes. #### Response Example (Array of ts-morph Modifier Nodes) ``` -------------------------------- ### GetAccessorDeclaration Source: https://github.com/dsherret/ts-morph/blob/latest/packages/ts-morph/wrapped-nodes.md Represents a get accessor declaration in a class or interface. ```APIDOC ## GetAccessorDeclaration ### Description Represents a get accessor declaration. ### Properties - **modifiers** (Modifier[]) - Modifiers applied to the accessor. - **name** (PropertyName) - The name of the accessor. - **body** (Block | undefined) - The body of the accessor. ``` -------------------------------- ### Function Declarations - Retrieval Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/functions.md Demonstrates how to retrieve function declarations from source files, namespaces, or function bodies. ```APIDOC ## Function Declarations - Retrieval ### Description Retrieve function declarations from source files, other namespaces, or function bodies. ### Method Various methods available on `SourceFile` and other nodes. ### Endpoints - `sourceFile.getFunctions()` - `sourceFile.getFunction(name: string)` - `sourceFile.getFunction(condition: (func: FunctionDeclaration) => boolean)` ### Request Example ```ts const functions = sourceFile.getFunctions(); const function1 = sourceFile.getFunction("Function1"); const firstFunctionWithChildFunction = sourceFile.getFunction(f => f.getFunctions().length > 0); ``` ### Response - `FunctionDeclaration[]`: An array of function declarations. - `FunctionDeclaration | undefined`: The found function declaration or undefined if not found. ### Response Example ```ts // For sourceFile.getFunctions() [ // FunctionDeclaration objects... ] // For sourceFile.getFunction(...) { // FunctionDeclaration object or undefined } ``` ``` -------------------------------- ### Get Interface Members Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/interfaces.md Retrieve all members of an interface declaration. ```typescript const members = interfaceDeclaration.getMembers(); ``` -------------------------------- ### In-Memory File System Type Resolution (Default) Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/file-system.md Demonstrates how the default script target of ES5 with an in-memory file system can lead to 'any' type resolution for certain types. ```typescript const project = new Project({ useInMemoryFileSystem: true }); const sourceFile = project.createSourceFile( "index.ts", `const mySet = new Set();`, ); const mySetDecl = sourceFile.getVariableDeclarationOrThrow("mySet"); console.log(mySetDecl.getType().getText()); // any ``` -------------------------------- ### Get Signature Declaration Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/signatures.md Retrieves the declaration node for a signature. ```typescript const declaration = signature.getDeclaration(); ``` -------------------------------- ### Get Decorators Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/decorators.md Retrieve all decorators associated with a class declaration. ```APIDOC ## Get Decorators ### Description Retrieve all decorators associated with a class declaration. ### Method `getDecorators()` ### Endpoint N/A (Method on ClassDeclaration node) ### Parameters None ### Request Example ```ts const decorators = classDeclaration.getDecorators(); ``` ### Response - `Decorator[]` - An array of decorator nodes. ``` -------------------------------- ### Copy Directory Immediately Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/directories.md Copies a directory to a new location immediately, without requiring `project.save()`. ```typescript await directory.copyImmediately("../otherDir"); ``` ```typescript directory.copyImmediatelySync("../otherDir2"); ``` -------------------------------- ### Get Enum Members Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/enums.md Retrieve all members of an enum declaration. ```typescript const members = enumDeclaration.getMembers(); ``` -------------------------------- ### Create Source File Source: https://github.com/dsherret/ts-morph/blob/latest/packages/bootstrap/readme.md Creates a new source file within the project with the specified file name and content. This method is synchronous. ```typescript const sourceFile = project.createSourceFile("MyClass.ts", "class MyClass {}"); ``` -------------------------------- ### Copying Source Files Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/source-files.md Create a copy of a source file to a new location, with options to overwrite existing files and copy to a specific directory. Supports immediate copying. ```APIDOC ## Copying Source Files ### Description Copy a source file to a new location. This operation can optionally overwrite existing files and update module specifiers. ### Methods - **copy(newPath: string, options?: { overwrite?: boolean }): SourceFile**: Copies the source file to `newPath`. If `overwrite` is `true`, it will overwrite an existing file at `newPath`. - **copyToDirectory(directory: string | Directory)**: Copies the source file to the specified directory. - **copyImmediately(newPath: string): Promise** - **copyImmediatelySync(newPath: string): SourceFile** ### Example ```ts // Copy to a new file name const newSourceFile = sourceFile.copy("newFileName.ts"); // Copy and overwrite if file exists const otherSourceFile = sourceFile.copy("other.ts", { overwrite: true }); // Copy to a specific directory sourceFile.copyToDirectory("/some/dir"); // Asynchronously copy immediately await sourceFile.copyImmediately("NewFile.ts"); // Synchronously copy immediately sourceFile.copyImmediatelySync("NewFile2.ts"); ``` ### Note If necessary, this will automatically update the module specifiers of the relative import and export declarations in the copied file. ``` -------------------------------- ### Get Identifier Type Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/identifiers.md Retrieves the TypeScript type of an identifier. ```typescript const identifierType = identifier.getType(); ``` -------------------------------- ### Standardize Add Source File Methods Source: https://github.com/dsherret/ts-morph/blob/latest/packages/ts-morph/breaking-changes.md Methods for adding source files if they exist have been standardized. Use `addExistingSourceFileIfExists` and `addExistingDirectoryIfExists`. ```typescript addSourceFileIfExists ``` ```typescript addExistingSourceFileIfExists ``` ```typescript addDirectoryIfExists ``` ```typescript addExistingDirectoryIfExists ``` -------------------------------- ### Function Declarations - Overloads Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/functions.md Details how to work with function overloads, including retrieval, checking, and adding/removing. ```APIDOC ## Function Declarations - Overloads ### Description Manage function overloads, including retrieving them, checking if a declaration is an overload or implementation, and adding/removing overloads. ### Method - `.getOverloads()` - `.isOverload()` - `.isImplementation()` - `.addOverload(options: AddFunctionDeclarationOptions)` - `.addOverloads(overloads: AddFunctionDeclarationOptions[])` - `.insertOverload(index: number, options: AddFunctionDeclarationOptions)` - `.insertOverloads(index: number, overloads: AddFunctionDeclarationOptions[])` ### Endpoint Methods on `FunctionDeclaration`. ### Parameters - `options` (AddFunctionDeclarationOptions): Configuration for the overload to add. - `index` (number): The index for insertion. ### Request Example ```ts // Get overloads const overloads = functionDeclaration.getOverloads(); // Check if it's an overload or implementation const isOverload = functionDeclaration.isOverload(); const isImplementation = functionDeclaration.isImplementation(); // Add an overload functionDeclaration.addOverload({ returnType: "string" }); ``` ### Response - `FunctionDeclaration[]`: An array of overload declarations. - `boolean`: Result of `isOverload()` and `isImplementation()`. - `FunctionDeclaration`: The newly added overload. ``` -------------------------------- ### Get Alias Symbol Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/types.md Retrieve the alias symbol for a type alias. ```typescript const aliasSymbol = type.getAliasSymbol(); ``` -------------------------------- ### Get Project Pre-Emit Diagnostics Source: https://github.com/dsherret/ts-morph/blob/latest/docs/setup/diagnostics.md Retrieve all syntactic, semantic, global, options, and configuration file parsing diagnostics for the entire project. This is useful for a comprehensive check before compilation. ```typescript const diagnostics = project.getPreEmitDiagnostics(); ``` -------------------------------- ### Get Call Signatures Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/types.md Retrieve the call signatures associated with a type. ```typescript const callSignatures = type.getCallSignatures(); ``` -------------------------------- ### Implementations Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/interfaces.md Retrieve implementations of an interface. ```APIDOC ## Implementations ### Description Get the implementations of an interface. This is similar to the "go to implementation" command in IDEs. ### Method - `getImplementations(): FunctionDeclaration[] | MethodDeclaration[] | ClassDeclaration[]` ### Endpoint Called on an `InterfaceDeclaration` object. ### Parameters None ### Request Example ```ts const implementations = interfaceDeclaration.getImplementations(); ``` ### Response #### Success Response (200) - `FunctionDeclaration[] | MethodDeclaration[] | ClassDeclaration[]`: An array of declarations that implement the interface. #### Response Example ```json [ { "kind": 105, // SyntaxKind.ClassDeclaration "name": { "kind": 79, // SyntaxKind.Identifier "text": "MyClass" }, "heritageClauses": [ { "token": 1, // SyntaxKind.ExtendsKeyword "types": [ { "kind": 107, // SyntaxKind.ExpressionWithTypeArguments "expression": { "kind": 79, // SyntaxKind.Identifier "text": "MyInterface" } } ] } ] } ] ``` ``` -------------------------------- ### Get Base Types Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/interfaces.md Retrieve the base types of an interface declaration. ```typescript const baseTypes = interfaceDeclaration.getBaseTypes(); ``` -------------------------------- ### Get Base Types Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/types.md Retrieve the base types of a given type. ```typescript const baseTypes = type.getBaseTypes(); ``` -------------------------------- ### Create Child Directory Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/directories.md Create a new directory as a child of an existing directory. ```typescript const childDir = directory.createDirectory("childDir"); ``` -------------------------------- ### Emit Directory Contents Source: https://github.com/dsherret/ts-morph/blob/latest/docs/navigation/directories.md Generate JavaScript and declaration files for the contents of a directory. Check `result.getEmitSkipped()` to confirm success. `emitSync()` is available but can be slow. ```typescript // always check result.getEmitSkipped() to make sure the emit was successful const result = await directory.emit(); directory.emitSync(); // slow ``` -------------------------------- ### Getting Exported Declarations Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/exports.md Retrieving all exported declarations from a file or module. ```APIDOC ## Getting Exported Declarations ### Description The exported declarations of a file or module can be retrieved via `.getExportedDeclarations()`. This will return a map keyed on the export name with a value of the exported declarations for that name. ### Method - `getExportedDeclarations(): ExportedDeclarations` ### Example ```ts import { ExportedDeclarations, Project } from "ts-morph"; const project = new Project(); project.addSourceFilesAtPaths("**/*.ts"); const mainFile = project.getSourceFileOrThrow("main.ts"); for (const [name, declarations] of mainFile.getExportedDeclarations()) console.log(`${name}: ${declarations.map(d => d.getText()).join(", ")}`); ``` ### Output Example ``` Class1: export class Class1 {} Class2: export class Class2 {} AliasedInterface: export interface Interface1 {} MergedNamespace: namespace MergedNamespace { let t; }, namespace MergedNamespace { let u; } default: 5 ``` ``` -------------------------------- ### Get Union Types Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/types.md Extract all types that form a union type. ```typescript const unionTypes = type.getUnionTypes(); ``` -------------------------------- ### Function Declarations - Name Handling Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/functions.md Explains how to handle function names, noting that function declarations may not always have a name. ```APIDOC ## Function Declarations - Name Handling ### Description Handles the retrieval and understanding of function names, acknowledging that anonymous functions exist. ### Method - `.getName()` - `.getNameNode()` ### Endpoint Methods on `FunctionDeclaration`. ### Parameters None directly for name retrieval, but the methods return nullable values. ### Response - `string | undefined`: The name of the function declaration, or undefined if it's anonymous. - `Identifier | undefined`: The AST node for the function name, or undefined if anonymous. ### Response Example ```ts // If functionDeclaration has a name 'myFunc' console.log(functionDeclaration.getName()); // Output: "myFunc" // If functionDeclaration is anonymous console.log(functionDeclaration.getName()); // Output: undefined ``` ``` -------------------------------- ### Get Intersection Types Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/types.md Extract all types that form an intersection type. ```typescript const intersectionTypes = type.getIntersectionTypes(); ``` -------------------------------- ### Get Extends Expressions Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/interfaces.md Retrieve the extends expressions for an interface declaration. ```typescript const extendsExpressions = interfaceDeclaration.getExtends(); ``` -------------------------------- ### Get Type of Node Source: https://github.com/dsherret/ts-morph/blob/latest/docs/details/types.md Access the type of a node by calling `.getType()`. ```typescript const type = parameter.getType(); ```