TypeScript Compiler API

getEditsForRefactor()

Computes edits for a selected refactor action. Use names returned by getApplicableRefactors for the same document version, not UI labels. Handle undefined and notApplicableReason. Apply edits across files, honor optional rename locations, and validate the result. The example verifies a simple extraction, not universal behavior preservation. Baseline: TypeScript 5.8.3. Run locally with Node.js; this is not a ByteMind CodeRunner exercise.

Formal Syntax & Structure

typescript syntaxtypescript
service.getEditsForRefactor(fileName: string, formatOptions: ts.FormatCodeSettings, positionOrRange: number | ts.TextRange, refactorName: string, actionName: string, preferences: ts.UserPreferences | undefined, interactiveRefactorArguments?: ts.InteractiveRefactorArguments): ts.RefactorEditInfo | undefined

Parameters & Attributes

NameTypeDescription
fileNamestringAbsolute path of a host-managed source file.
formatOptionsts.FormatCodeSettingsFormatting settings for generated edits.
positionOrRangenumber | ts.TextRangeCursor position or selection with pos and end.
refactorNamestringSelected refactor group name.
actionNamestringSelected action name.
preferencests.UserPreferences | undefinedEditor preferences; pass undefined for defaults.
interactiveRefactorArgumentsts.InteractiveRefactorArgumentsArguments for an interactive action.

Working Example

Example Snippettypescript
// Use a new empty directory. Install: npm install --save-exact typescript@5.8.3// File: example.cjs (omit this label)const ts = require("typescript");const assert = require("node:assert/strict");const path = require("node:path");// Project documents live in memory; compiler libraries use the local filesystem.function workspace(initial, extraOptions = {}) {  const files = new Map(Object.entries(initial).map(([name, text]) =>    [path.resolve(name), { text, version: 0 }]));  const options = { strict: true, target: ts.ScriptTarget.ES2022,    module: ts.ModuleKind.CommonJS, types: [], noEmit: true, ...extraOptions };  const key = name => path.resolve(name);  const read = name => files.get(key(name))?.text ?? ts.sys.readFile(name);  const host = {    getCompilationSettings: () => options,    getScriptFileNames: () => [...files.keys()],    getScriptVersion: name => String(files.get(key(name))?.version ?? 0),    getScriptSnapshot: name => { const text = read(name);      return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text); },    getCurrentDirectory: () => process.cwd(),    getDefaultLibFileName: opts => ts.getDefaultLibFilePath(opts),    fileExists: name => files.has(key(name)) || ts.sys.fileExists(name),    readFile: read,    readDirectory: ts.sys.readDirectory,    directoryExists: ts.sys.directoryExists,    getDirectories: ts.sys.getDirectories,    useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,    getNewLine: () => "\n"  };  function edit(name, text) {    const file = files.get(key(name));    assert(file, "edit requires an existing file");    files.set(key(name), { text, version: file.version + 1 });  }  return { host, edit, read, key };}const format = { indentSize: 2, tabSize: 2, convertTabsToSpaces: true,  newLineCharacter: "\n", insertSpaceAfterCommaDelimiter: true,  insertSpaceBeforeAndAfterBinaryOperators: true,  insertSpaceAfterKeywordsInControlFlowStatements: true,  semicolons: ts.SemicolonPreference.Insert };function apply(text, changes) {  // All spans refer to the same original snapshot; edit from right to left.  for (const change of [...changes].sort((a,b)=>b.span.start-a.span.start)) {    const {start,length}=change.span;    text=text.slice(0,start)+change.newText+text.slice(start+length);  }  return text;}function applyFiles(w, edits) {  for (const edit of edits) w.edit(edit.fileName, apply(w.read(edit.fileName), edit.textChanges));}function run(initial, fn, options = {}) {  const w=workspace(initial,options), service=ts.createLanguageService(w.host);  try { fn(w,service,w.key("main.ts")); } finally { service.dispose(); }}run({"main.ts":"function f() { return 2 + 3; }"},(w,s,f)=>{ const text=w.read(f),pos=text.indexOf("2 + 3"),range={pos,end:pos+5}; const groups=s.getApplicableRefactors(f,range,{}); const group=groups.find(r=>r.actions.some(a=>a.kind?.startsWith("refactor.extract.constant")&&!a.notApplicableReason)); assert(group); const action=group.actions.find(a=>a.kind?.startsWith("refactor.extract.constant")&&!a.notApplicableReason); const result=s.getEditsForRefactor(f,format,range,group.name,action.name,{}); assert(result&&!result.notApplicableReason); assert(result.edits.length); assert.equal(w.read(f),text); applyFiles(w,result.edits); assert.match(w.read(f),/const \w+ = 2 \+ 3/); assert.deepEqual(s.getSyntacticDiagnostics(f),[]); assert.deepEqual(s.getSemanticDiagnostics(f),[]); const js=ts.transpileModule(w.read(f)+"\nmodule.exports=f();",{compilerOptions:{module:ts.ModuleKind.CommonJS}}).outputText; const mod={exports:null}; new Function("module",js)(mod); assert.equal(mod.exports,5); console.log("extracted constant; result 5");});
// Run: node example.cjs// Expected stdout: extracted constant; result 5
TypeScript Reference