TypeScript 的错误信息是用英文写的,它们真的在试图帮助你。学会解读它们,每当出错时,就像有位高级工程师在你耳边低声提示。
TypeScript's error messages are written in English — and they're actually trying to help you. Learn to decode them, and you'll have a senior developer whispering in your ear every time something goes wrong.
代码精读
// Common TypeScript errors and their plain-English translations:
// ❌ Error: Type 'string' is not assignable to type 'number'
// 📖 Plain English: You tried to put text where a number belongs.
let age: number = 'twenty-five'; // ← TypeScript catches this!
// ❌ Error: Property 'email' does not exist on type 'User'
// 📖 Plain English: 'email' is not in the User blueprint.
interface User {
name: string;
age: number;
}
const user: User = { name: 'Alice', age: 30 };
console.log(user.email); // ← Property 'email' does not exist
// ❌ Error: Object is possibly 'undefined'
// 📖 Plain English: This value might not exist — handle that case!
const users = ['Alice', 'Bob'];
const first = users[0]; // type: string | undefined
console.log(first.toUpperCase()); // ← possibly undefined!
// ✅ Fix: check first!
if (first) console.log(first.toUpperCase());
💡 建议:把每一行代码大声用英文念出来,注释就是你的翻译。
单词讲解
assignable
/əˈsaɪnəbl/
adjective
可赋值的,可分配的
property
/ˈprɒpərti/
noun
属性(对象上的字段)
undefined
/ˌʌndɪˈfaɪnd/
noun / adjective
未定义的(值不存在)
interface
/ˈɪntərˌfeɪs/
noun
接口(TypeScript 中的类型蓝图)
理解检验
先在脑子里想一想——再点开看参考答案。
Q1: What does "not assignable" mean in plain English?
Q2: Why does TypeScript say "possibly undefined" instead of just letting the code run?
核心要点▼ 展开