A TypeScript library for code transformations using AST (Abstract Syntax Tree) transformers, powered by the ts-morph.
ts-codemod-lib provides utilities and ready-to-use transformers for automated TypeScript code transformations. It enables you to programmatically modify TypeScript source code through AST manipulation, making it ideal for large-scale refactoring tasks, enforcing type safety, and promoting immutability.
as const, convert to readonly types, replace any with unknown, and more# Using npm
npm add ts-codemod-lib
# Using pnpm
pnpm add ts-codemod-lib
# Using yarn
yarn add ts-codemod-lib
For CLI usage:
npm add -D ts-codemod-lib cmd-ts dedent ts-repo-utils
This library provides TypeScript AST transformers that can be used to automatically modify your TypeScript code. The transformers can be used individually or combined for more complex transformations.
appendAsConstTransformerAppends as const to array literals and object literals to make them readonly constants. This transformer helps in creating immutable data structures by automatically adding the TypeScript as const assertion.
Options:
applyLevel: 'all' or 'avoidInFunctionArgs' (default: 'avoidInFunctionArgs')
'avoidInFunctionArgs': Avoids adding as const inside function call arguments'all': Applies as const everywhereignorePrefixes: Array of string prefixes for identifiers that should not have as const added (default: ['mut_', '#mut_', '_mut_', 'draft'])Example:
// Before
const arr = [1, 2, 3];
const obj = { a: 1, b: 2 };
// After
const arr2 = [1, 2, 3] as const;
const obj2 = { a: 1, b: 2 } as const;
convertToReadonlyTransformerConverts TypeScript type definitions to readonly types. This transformer helps in creating more type-safe code by making types readonly where appropriate. It also normalizes nested readonly types (e.g., Readonly<Readonly<T>> becomes Readonly<T>).
Options:
ignorePrefixes: Array of string prefixes for identifiers that should not be made readonly (default: ['mut_', '#mut_', '_mut_', 'draft'])DeepReadonly.typeName: Custom name for the DeepReadonly type utility (default: "DeepReadonly")Example:
// Before
type User = {
id: number;
description: string;
preferences: Map<string, string>;
friendIds: number[];
mut_items: string[]; // With ignorePrefixes: ['mut_']
};
// After
type User2 = Readonly<{
id: number;
description: string;
preferences: ReadonlyMap<string, string>;
friendIds: readonly number[];
mut_items: string[]; // Not made readonly due to 'mut_' prefix
}>;
For more detailed transformation examples, see the test file which covers various scenarios including complex types, nested structures, and DeepReadonly transformations.
convertInterfaceToTypeTransformerConverts TypeScript interface declarations to type aliases. This transformer helps in maintaining consistency by using type aliases throughout the codebase.
Example:
// Before
interface User {
id: number;
name: string;
}
// After
type User2 = {
id: number;
name: string;
};
replaceAnyWithUnknownTransformerReplaces any type annotations with unknown for improved type safety. The unknown type requires type checking before operations, making your code more robust. For function parameters with rest arguments, (...args: any) => R is converted to (...args: readonly unknown[]) => R.
Example:
// Before
const getValue = (data: any): any => data.value;
const sortValues = (...args: any): any =>
args.toSorted((a: any, b: any) => a - b);
// After
const getValue2 = (data: unknown): unknown => (data as any).value;
const sortValues2 = (...args: readonly unknown[]): unknown =>
(args as any).toSorted((a: any, b: any) => a - b);
For more detailed transformation examples, see the test file which covers various scenarios including function parameters, return types, and variable declarations.
replaceRecordWithUnknownRecordTransformerReplaces Record<string, unknown> and Readonly<Record<string, unknown>> with UnknownRecord for better type safety and consistency. This transformer also handles index signatures [k: string]: unknown in interfaces and type literals.
Example:
// Before
type Config = Record<string, unknown>;
type ReadonlyConfig = Readonly<Record<string, unknown>>;
type Data = Record<string, unknown>;
// After
type Config2 = UnknownRecord;
type ReadonlyConfig2 = UnknownRecord;
type Data2 = UnknownRecord;
// transformer-ignore-next-line comment will be skipped.
// transformer-ignore-next-line append-as-const, replace-any-with-unknown/* transformer-ignore */ comment will be skipped entirely.Examples:
Example using // transformer-ignore-next-line:
// Before
type Config = {
apiKey: string;
// transformer-ignore-next-line
mutableOptions: string[]; // This line will not be made Readonly
settings: { timeout: number };
};
// After applying convertToReadonlyTransformer
type Config2 = Readonly<{
apiKey: string;
// transformer-ignore-next-line
mutableOptions: string[]; // Not made Readonly because it was skipped
settings: Readonly<{ timeout: number }>;
}>;
Example using /* transformer-ignore */:
// Before
type Data = { value: any };
const items = [1, 2, 3];
// After applying any transformer (e.g., replaceAnyWithUnknownTransformer, appendAsConstTransformer)
// No changes will be made to this file.
type Data2 = { value: any };
const items2 = [1, 2, 3];
This package provides command-line tools for common TypeScript transformations:
Appends as const to array literals and object literals to make them readonly constants.
npx append-as-const <baseDir> [--exclude <pattern>] [--silent]
Converts TypeScript interface declarations to type aliases.
npx convert-interface-to-type <baseDir> [--exclude <pattern>] [--silent]
Adds readonly modifiers to type definitions throughout your codebase.
npx convert-to-readonly <baseDir> [--exclude <pattern>] [--silent]
Replaces any type annotations with unknown for improved type safety.
npx replace-any-with-unknown <baseDir> [--exclude <pattern>] [--silent]
Replaces Record<string, unknown> with UnknownRecord for better type safety.
npx replace-record-with-unknown-record <baseDir> [--exclude <pattern>] [--silent]
Common Options:
baseDir: Base directory to scan for TypeScript files--exclude: Glob patterns to exclude (e.g., "src/generated/**/*.mts")--silent: Suppress output messagesYou can use the astTransformerToStringTransformer utility to apply these transformers to source code strings:
import dedent from 'dedent';
import {
appendAsConstTransformer,
convertInterfaceToTypeTransformer,
convertToReadonlyTransformer,
replaceAnyWithUnknownTransformer,
replaceRecordWithUnknownRecordTransformer,
transformSourceCode,
} from 'ts-codemod-lib';
const originalCode = dedent`
export interface A {
name?: string;
point: [x: number, y: number, z?: number];
meta: {
description?: string;
tags: string[];
attributes: Record<string, unknown>;
data?: any;
};
}
export const obj = {
point: [1, 2],
meta: {
tags: ['example', 'test'],
attributes: {
key1: 'value1',
key2: 42,
},
},
} satisfies A;
export const arr = ['a', {}, 0];
`;
const isTsx = false;
// Apply transformations to source code
const transformedCode = transformSourceCode(originalCode, isTsx, [
convertInterfaceToTypeTransformer(),
replaceRecordWithUnknownRecordTransformer(),
convertToReadonlyTransformer(),
appendAsConstTransformer(),
replaceAnyWithUnknownTransformer(),
]);
const expected = dedent`
export type A = Readonly< {
name?: string;
point: (readonly [x: number, y: number, z?: number]);
meta: Readonly< {
description?: string;
tags: (readonly string[]);
attributes: UnknownRecord;
data?: unknown;
}>;
}>;
export const obj = {
point: [1, 2],
meta: {
tags: ['example', 'test'],
attributes: {
key1: 'value1',
key2: 42,
},
},
} as const satisfies A;
export const arr = ['a', {}, 0] as const;
`;
if (import.meta.vitest !== undefined) {
test('transformSourceCode', () => {
assert.isTrue(transformedCode === expected);
});
}
Note: It is recommended to apply all transformers at once using transformSourceCode rather than applying each transformer individually.
This is more efficient as it avoids the overhead of parsing and printing before and after applying each AST transformation.
src Directoryimport * as fs from 'node:fs/promises';
import {
appendAsConstTransformer,
convertInterfaceToTypeTransformer,
convertToReadonlyTransformer,
replaceAnyWithUnknownTransformer,
replaceRecordWithUnknownRecordTransformer,
transformSourceCode,
} from 'ts-codemod-lib';
for await (const filePath of fs.glob('path/to/src/**/*.{mts,tsx}')) {
if (filePath.endsWith('.d.mts')) {
console.log(`Skipping declaration file: ${filePath}`);
continue;
}
console.log(`Processing file: ${filePath}`);
const originalCode = await fs.readFile(filePath, 'utf8');
const isTsx = filePath.endsWith('.tsx') || filePath.endsWith('.jsx');
// Apply transformations to source code
const transformedCode = transformSourceCode(originalCode, isTsx, [
convertInterfaceToTypeTransformer(),
replaceRecordWithUnknownRecordTransformer(),
convertToReadonlyTransformer(),
appendAsConstTransformer(),
replaceAnyWithUnknownTransformer(),
]);
await fs.writeFile(filePath, transformedCode, 'utf8');
}
Run:
node codemod.mjs
Types within JSDoc comments are not transformed.
// Before
/**
* Processes user data.
* @param {object} user - The user object.
* @param {string[]} user.roles - User roles.
* @returns {object} Processed data.
*/
function processUser(user: { name: string; roles: string[] }): {
success: boolean;
} {
// ... implementation ...
return { success: true };
}
// After applying convertToReadonlyTransformer
/**
* Processes user data.
* @param {object} user - The user object. // JSDoc type is not changed
* @param {string[]} user.roles - User roles. // JSDoc type is not changed
* @returns {object} Processed data. // JSDoc type is not changed
*/
function processUser(
user: Readonly<{ name: string; roles: readonly string[] }>,
): Readonly<{ success: boolean }> {
// ... implementation ...
return { success: true };
}
Comment positions might change due to the heuristics used for restoring comments in the code.
ts-codemod-lib includes preprocessing to identify all detached comments that the printer cannot restore and reattaches them to the immediately preceding or succeeding node, making them printable. However, the determination of whether to attach the comment before or after the node is heuristic, so the comment might move to a different position than in the original code.// transformer-ignore-next-line comment.git clone https://github.com/noshiro-pf/ts-codemod-lib.git
git submodule update --init --recursive
pnpm i
AGENTS.md in the common repository (common-agent-config)git submodule update --remote --merge
git add agents/common
git commit -m "Update AGENTS.md"