对象类型定义
在 TypeScript 中,对象类型定义是通过接口(interface)来实现的。它们允许你定义一个对象的形状,包括属性和方法。 下面是一些基本的示例: interface Animal { species: string; age: number; makeSound: () => void; } const dog: Animal = { species: "Dog", age: 5, makeSound() { console.log("Woof!"); } }; 使用 interface 定义可选属性和只读属性: interface Car { make: string; model: string; year?: number; // 可选属性 readonly vin: string; // 只读属性 } const car: Car = { make: "Toyota", model: "Corolla", vin: "1HGCM82633A123456" }; 使用 interface 定义任意属性: interface User { id: number; name: string; [key: string]: any; // 任意属性 } const user: User = { id: 1, name: "Alice", age: 30, isAdmin: true }; 需要注意的是,一旦定义了任意属性,那么确定属性和可选属性的类型都必须是它的类型的子集: interface User { id: number; name: string; [key: string]: string; } const user: User = { id: 1, name: "Alice", age: 30, isAdmin: true }; // Property 'id' of type 'number' is not assignable to 'string' index type 'string'. // Type 'number' is not assignable to type 'string'. // Type 'boolean' is not assignable to type 'string'. 上面的例子任意属性的类型为 string,但是 id 的类型为 number,这会导致类型不匹配的错误。 ...