对象类型 in TypeScript
描述对象 shapes 使用 inline 类型, 接口, 索引 signatures, and 记录.
你将学到
- Inline 对象类型 literals 对比 named 接口
- 可选, readonly, and excess 属性检查
- 索引 signatures for 动态-键对象
- Using 记录<K, V> for keyed 映射
概念讲解
Object Type Literals
你可以describe an object shape inline without naming it: let 用户: { id: 数字; name: 字符串 } = { id: 1, name: "Alice" }. Inline types are convenient for one-off shapes, but for reusable types you should name them with an interface or type alias. Inline types are common in function parameters: 函数 log(用户: { name: 字符串 }): 空.
Index Signatures
When an object has dynamic keys (like a lookup table), use an index signature: { [键: 字符串]: 数字 } means every string key maps to a number. This is useful for caches, frequency maps, and configuration objects. The 记录<K, V> utility type is a cleaner alternative: 记录<字符串, 数字> is equivalent to { [键: 字符串]: 数字 } but more readable.
Property Modifiers
Optional properties (email?: 字符串) may be absent. Readonly properties (readonly id: 数字) cannot be reassigned. TypeScript performs excess property checking on object literals — assigning { id: 1, name: "Alice", extra: 真 } to a type without extra is an error. This catches typos but can be bypassed by assigning through an intermediate variable.
示例代码
// Inline object type — good for one-off shapes.
let user: { id: number; name: string; email?: string } = {
id: 1,
name: "Alice",
};
// Index signature — dynamic string keys, all number values.
let scores: { [key: string]: number } = {
math: 90,
science: 85,
};
// Record<K, V> — cleaner syntax for keyed maps.
let config: Record<string, boolean> = {
debug: true,
verbose: false,
};
// Readonly and optional combined.
type Account = {
readonly id: number;
name: string;
readonly createdAt: Date;
};
const acc: Account = { id: 1, name: "Bob", createdAt: new Date() };
// acc.id = 2; // ❌ Error: readonly
console.log(user.name, scores.math, config.debug, acc.name);
Inline 类型工作 for one-off shapes. 索引 signatures { [键: 字符串]: V } or 记录<字符串, V> handle 动态键. 可选 (?) and readonly modifiers refine 属性.
动手试一试
- JSON 到 TypeScript
Generate 对象类型 and 接口从 JSON 示例.
- JSON Validator
验证那个 JSON matches 你的对象类型之前 using 它.
常见错误
错误写法
Using 索引 signature 当键 是 actually known and 有限
正确做法
如果你 know 所有可能键, 列表它们 explicitly as named 属性. 索引 signatures lose 键-level 类型 safety and 允许任何字符串键.
错误写法
Excess 属性错误当 spreading 对象
正确做法
Excess 属性检查 applies 到对象 literals. Spreading or assigning 通过变量 bypasses 它. 如果 extra 属性是 intentional, widen 目标类型.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。