AI 編寫的 TypeScript:四類 tsc 無法發現的執行時陷阱與審查要點
Four runtime bugs that pass tsc: what to look for when you review AI-written TypeScript
文章整理 AI 編寫 TypeScript 時,tsc 無法攔截的執行時陷阱,並示範如何在輸入邊界驗證資料。例子包括型別斷言不會執行驗證、Number("") 會得到 0,以及浮點數運算造成金額精度誤差。作者建議檢查請求資料的 as、用戶輸入的數字轉換及價格運算,並指出所有程式碼均在 Node 22 執行。
When an AI assistant writes a route handler for you, it compiles. That is the easy part. The bugs that survive a quick review are the ones the compiler cannot see: values that have the right type on paper and the wrong value at runtime.
This post is for developers who already review AI-assisted diffs (or write TypeScript for APIs) and want a short list of runtime traps to check for. Each one is a script you can paste and run. Nothing here is a benchmark or a claim about how often any tool makes these mistakes. These are shapes I look for in review, and I ran every snippet below on Node 22.
1. as is not validation
A handler reads JSON and asserts the type:
type CreateItem = { name: string; quantity: number; unitPriceCents: number };
// 1. A type assertion does not check anything at runtime.
const body: unknown = JSON.parse('{"name":"Pen","quantity":"5","unitPriceCents":250}');
const item = body as CreateItem;
console.log("1 total:", item.quantity * item.unitPriceCents, "| typeof quantity:", typeof item.quantity);
console.log("1 sum with +:", item.quantity + item.unitPriceCents);
Output:
1 total: 1250 | typeof quantity: string
1 sum with +: 5250
The multiplication works by accident, because * coerces the string. The + concatenates. Same object, same type, two different answers, and tsc is happy with both. If the order total ever goes through +, you charge 5250 cents instead of 1250.
2. Number() treats empty strings as zero
A query parameter like ?limit= or a blank form field becomes 0, and Number.isFinite agrees it is a number:
for (const raw of ["", " ", "12abc", "1e3", "0x10"]) {
console.log(`Number(${JSON.stringify(raw)}) =`, Number(raw));
}
console.log(Number.isFinite(Number("")));
Number("") = 0
Number(" ") = 0
Number("12abc") = NaN
Number("1e3") = 1000
Number("0x10") = 16
true
A limit of 0, a price of 0, or a page of 1000 (from 1e3) can slip through a check that only asks "is it a finite number?".
3. Money in floats
console.log(0.1 + 0.2, 19.99 * 100, Math.round(19.99 * 100), 1.005 * 100);
0.30000000000000004 1998.9999999999998 1999 100.49999999999999
Store money as integer minor units (cents), and round once, at the edge, on purpose. If the assistant wrote price * 100 somewhere, check what it does with 19.99.
4. The fix: parse at the boundary
Take unknown, check every field, return a typed value or throw. No library needed for a small body. A schema library such as Zod or Valibot does the same job with less code once you have more than a few fields.
type CreateItem = { name: string; quantity: number; unitPriceCents: number };
function isPositiveInt(v: unknown): v is number {
return typeof v === "number" && Number.isInteger(v) && v > 0;
}
export function parseCreateItem(input: unknown): CreateItem {
if (typeof input !== "object" || input === null) throw new Error("body must be an object");
const o = input as Record<string, unknown>;
if (typeof o.name !== "string" || o.name.trim() === "") throw new Error("name");
if (!isPositiveInt(o.quantity)) throw new Error("quantity");
if (!isPositiveInt(o.unitPriceCents)) throw new Error("unitPriceCents");
return { name: o.name.trim(), quantity: o.quantity, unitPriceCents: o.unitPriceCents };
}
The one as in there is safe because it comes right after the typeof and null checks, and every field is checked before use. Run against three inputs:
ok: { name: 'Pen', quantity: 5, unitPriceCents: 250 }
rejected: quantity
rejected: name
For query parameters, accept only the shape you expect and fall back otherwise:
function parseLimit(raw: string | null, fallback = 20): number {
if (raw === null || !/^\d{1,3}$/.test(raw)) return fallback;
const n = Number(raw);
return n >= 1 && n <= 100 ? n : fallback;
}
// [null, "", " ", "abc", "0", "50", "500"] -> 20,20,20,20,20,50,20
A 60-second review pass
- Search the diff for
ason anything that came from a request, a file, orJSON.parse. Each one needs a parser behind it. - Search for
Number(,parseInt(andparseFloat(on user input. Ask what happens with an empty string. - Search for
* 100,/ 100andtoFixednear prices. - Check that a failing input has a test, and that the test fails without the fix.
This catches a small slice of what can go wrong. It will not replace tests, authorization review or a security audit.
Disclosure: this article and its code were produced with AI assistance. Every code block was run on Node 22 and the outputs shown are the real outputs.
來源:DEV Community · dev.to