Skip to content

Instantly share code, notes, and snippets.

@max-scopp
Created August 21, 2025 20:48
Show Gist options
  • Select an option

  • Save max-scopp/61bd1b818e5c54e6f44cd757aa977dac to your computer and use it in GitHub Desktop.

Select an option

Save max-scopp/61bd1b818e5c54e6f44cd757aa977dac to your computer and use it in GitHub Desktop.
import { Project, SyntaxKind } from "ts-morph";
// Step 1: create a ts-morph project
const project = new Project({
useInMemoryFileSystem: true,
compilerOptions: { strict: true }
});
// Step 2: insert your template source
const source = project.createSourceFile("temp.ts", `
export function MY_FUNC(ARG1, ARG2) {
return { ...ARG1, b: ARG2 };
}
`);
// Step 3: look up the function declaration
const func = source.getFunctionOrThrow("MY_FUNC");
// === Postprocess ===
// Rename function name
func.rename("abc");
// Rename parameters
const [arg1, arg2] = func.getParameters();
arg1.rename("method");
arg2.rename("count");
// Add type annotations
arg1.setType("string");
arg2.setType("number");
// Step 4: optionally inspect inferred return type
const signature = func.getSignature();
console.log("Return type:", signature.getReturnType().getText());
// Step 5: print the transformed source
console.log(source.getFullText());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment