实战技巧
常见类型错误与解决
分析常见 TS 编译错误、类型不匹配修复策略
常见类型错误与解决
TypeScript 的类型错误是帮助你写正确代码的提示。学会解读这些错误至关重要。
学完本章你将: 识别常见 TS 编译错误并快速修复。
TS2322: 类型不匹配
typescript
// ❌ let name: number = "Alice";
// Error: Type 'string' is not assignable to type 'number'
// ✅ 修复:使用正确的类型
let name: string = "Alice";
let age: number = 25;
TS2339: 属性不存在
typescript
// ❌ { name: "Alice" }.age;
// Error: Property 'age' does not exist on type '{ name: string }'
// ✅ 修复:先定义接口
interface User { name: string; age?: number }
const user: User = { name: "Alice" };
console.log(user.age); // ✅ 可选属性返回 undefined
TS2345: 参数类型不匹配
typescript
// ❌ Math.round("hello");
// Error: Argument of type 'string' is not assignable to parameter of type 'number'
// ✅ 先验证再使用
function safeRound(value: unknown): number {
const num = Number(value);
if (isNaN(num)) throw new Error("不是数字");
return Math.round(num);
}
TS18048: 可能为 undefined
typescript
// ❌ const el = document.getElementById("app"); el.innerHTML = "hi";
// Error: 'el' is possibly 'null'
// ✅ 方式 1:类型守卫
const el = document.getElementById("app");
if (el) { el.innerHTML = "hi"; }
// ✅ 方式 2:非空断言
document.getElementById("app")!.innerHTML = "hi";
// ✅ 方式 3:可选链(安全访问)
document.getElementById("app")?.setAttribute("title", "hello");
TS7006: 隐式 any
typescript
// ❌ function add(a, b) { return a + b; }
// Error: Parameter 'a' implicitly has an 'any' type
// ✅ 添加类型注解
function add(a: number, b: number): number {
return a + b;
}