Renaming TypeScript interfaces with ts-morph
Here’s how I removed the I
prefixes of all interfaces in a project: IDog
becomes Dog
.
- Create a file with the codemod, src/remove-prefixes.ts:
- Install dependencies:
npm install --save-dev ts-morph
- Run the codemod:
ts-node --compiler-options '{"module": "commonjs"}' src/remove-prefixes.ts
Note We need to override compiler options here because our project is using webpack and ECMAScript modules aren’t transpiled, which is required for Node.js.
Caveats
This codemod doesn’t do anything with naming conflict. For example, if we already have a Dog
component or class and we’re importing the IDog
interface into the same file, we’ll have a naming conflict: both, the component and the interface will be called Dog
.