Rename and code fixes
Concept and boundary
Rename eligibility and returned edits are separate from applying them. Inspect locations and any prefix/suffix text, apply nonoverlapping edits against the original snapshot, then update versions and re-check. Code fixes also return candidate changes, not guarantees of correctness across external consumers.
Local tooling setup
For each workshop use a fresh folder. Install the pinned compiler with npm install --save-dev typescript@5.8.3, then create the listed files and run node example.cjs with Node.js 22.16.0. Assertions fail if the expected behavior changes. These are local JavaScript tooling scripts, not browser CodeRunner tasks; they do not independently type-check the tooling source.
Workshop 1: find-rename-locations
Revisit reference fixture ts-api-find-rename-locations (historical V25, rerun in V74).
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) { 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 }; 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 w = workspace({"main.ts": "const count = 1;\nconst total = count + count;\nfunction other() { const count = 9; return count; }"});const file = w.key("main.ts");const service = ts.createLanguageService(w.host);try { const locations = service.findRenameLocations(file, w.read(file).indexOf("count"), false, false, { providePrefixAndSuffixTextForRename: true }); assert.equal(locations.length, 3); let text = w.read(file); for (const loc of [...locations].sort((a,b)=>b.textSpan.start-a.textSpan.start)) { assert.equal(loc.fileName, file); const {start,length} = loc.textSpan; text = text.slice(0,start) + (loc.prefixText ?? "") + "amount" + (loc.suffixText ?? "") + text.slice(start+length); } assert(text.includes("const total = amount + amount;")); assert(text.includes("const count = 9; return count;")); w.edit("main.ts", text); assert.deepEqual(service.getSemanticDiagnostics(file), []); console.log("3 edits; shadow preserved; clean");} finally { service.dispose(); }Expected stdout (exit 0):
3 edits; shadow preserved; cleanWorkshop 2: get-code-fixes-at-position
Revisit reference fixture ts-api-get-code-fixes-at-position (historical V25, rerun in V74).
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) { 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 }; 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 w = workspace({"main.ts": "const item = { count: 1 };\nitem.coutn;"});const file = w.key("main.ts");const service = ts.createLanguageService(w.host);try { const ds = service.getSemanticDiagnostics(file); assert.deepEqual(ds.map(d=>d.code), [2551]); const d = ds[0]; const fixes = service.getCodeFixesAtPosition(file, d.start, d.start+d.length, [d.code], {}, {}); const fix = fixes.find(f=>f.changes.some(c=>c.textChanges.some(t=>t.newText === "count"))); assert(fix); assert.equal(fix.changes.length, 1); assert.equal(fix.changes[0].fileName, file); let text = w.read(file); for (const c of [...fix.changes[0].textChanges].sort((a,b)=>b.span.start-a.span.start)) { text = text.slice(0,c.span.start)+c.newText+text.slice(c.span.start+c.span.length); } assert(text.includes("item.count;")); w.edit("main.ts", text); assert.deepEqual(service.getSemanticDiagnostics(file), []); console.log("2551 -> clean");} finally { service.dispose(); }Expected stdout (exit 0):
2551 -> cleanPractice and recap
Apply a rename then query semantic diagnostics; try a conflicting new name separately.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Rename and code fixes — knowledge check
Check the concept and interpret the locally verified compiler tooling probes.
Which statement correctly describes Rename and code fixes?
What does workshop 1 (find-rename-locations) print when run unchanged with the specified compiler?
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) { 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 }; 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 w = workspace({"main.ts": "const count = 1;\nconst total = count + count;\nfunction other() { const count = 9; return count; }"});const file = w.key("main.ts");const service = ts.createLanguageService(w.host);try { const locations = service.findRenameLocations(file, w.read(file).indexOf("count"), false, false, { providePrefixAndSuffixTextForRename: true }); assert.equal(locations.length, 3); let text = w.read(file); for (const loc of [...locations].sort((a,b)=>b.textSpan.start-a.textSpan.start)) { assert.equal(loc.fileName, file); const {start,length} = loc.textSpan; text = text.slice(0,start) + (loc.prefixText ?? "") + "amount" + (loc.suffixText ?? "") + text.slice(start+length); } assert(text.includes("const total = amount + amount;")); assert(text.includes("const count = 9; return count;")); w.edit("main.ts", text); assert.deepEqual(service.getSemanticDiagnostics(file), []); console.log("3 edits; shadow preserved; clean");} finally { service.dispose(); }What does workshop 2 (get-code-fixes-at-position) print when run unchanged with the specified compiler?
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) { 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 }; 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 w = workspace({"main.ts": "const item = { count: 1 };\nitem.coutn;"});const file = w.key("main.ts");const service = ts.createLanguageService(w.host);try { const ds = service.getSemanticDiagnostics(file); assert.deepEqual(ds.map(d=>d.code), [2551]); const d = ds[0]; const fixes = service.getCodeFixesAtPosition(file, d.start, d.start+d.length, [d.code], {}, {}); const fix = fixes.find(f=>f.changes.some(c=>c.textChanges.some(t=>t.newText === "count"))); assert(fix); assert.equal(fix.changes.length, 1); assert.equal(fix.changes[0].fileName, file); let text = w.read(file); for (const c of [...fix.changes[0].textChanges].sort((a,b)=>b.span.start-a.span.start)) { text = text.slice(0,c.span.start)+c.newText+text.slice(c.span.start+c.span.length); } assert(text.includes("item.count;")); w.edit("main.ts", text); assert.deepEqual(service.getSemanticDiagnostics(file), []); console.log("2551 -> clean");} finally { service.dispose(); }