对应类型和索引签名
对象类型对象类型用于描述对象的结构——对象有哪些属性、每个属性的类型、是否可选、是否只读等。它是 TypeScript 中最核心、最常用的类型之一。对象类型的定义方式方式1匿名对象类型// 直接在变量声明中定义 let user: { id: number; username: string } { id: 1, username: alice }; // 函数参数 function printUser(user: { name: string; age: number }) { console.log(${user.name} is ${user.age} years old); }方式2接口Interfaceinterface User { id: number; name: string; email: string; } const user: User { id: 1, name: Alice, email: aliceexample.com };方式3类型别名Type Aliastype User { id: number; name: string; email: string; }; const user: User { id: 1, name: Alice, email: aliceexample.com };方式4类Classclass User { id: number; name: string; constructor(id: number, name: string) { this.id id; this.name name; } } const user: User new User(1, Alice);索引签名索引签名用于定义对象可以拥有的任意数量的属性并约束这些属性的键和值的类型。它解决了我不知道对象会有哪些具体属性的问题。type Obj { name: string; age: number; } // 这个类型非常精确 const alice: Obj { name: Alice, age: 25 }; // ✅ 完美匹配 // const bob: Obj { // name: Bob, // age: 30, // email: bobtest.com // ❌ 错误Obj 类型中没有定义 email // };给Obj加上一个索引签名它就从“固定形状”变成了“灵活字典”type FlexibleObj { name: string; age: number; // 索引签名允许添加任意字符串属性且值必须是 string 类型 [key: string]: string; }const alice: FlexibleObj { name: Alice, age: 25, // ❌ 报错注意这里 email: alicetest.com, // ✅ 现在可以添加额外属性了 city: Beijing, // ✅ 也可以添加其他属性 };当你写上[key: string]: string后就等于告诉 TypeScript“这个对象里的所有属性值都必须是string类型。”name: string符合要求。但age: number是数字不符合所以报错。如何修复1使用联合类型让索引签名的类型包含age的类型。[key: string]: string | number;2 [key: string]: any;