在 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,这会导致类型不匹配的错误。

interface 继承

接口可以通过继承来扩展其他接口的属性和方法:

interface User {
    id: number;
    name: string;
    age: number;
    isAdmin: boolean;
}

interface Employee extends User {
    employeeId: number;
    department: string;
}
const employee: Employee = {
    id: 1,
    name: "Alice",
    age: 30,
    isAdmin: true,
    employeeId: 1001,
    department: "Engineering"
};

总结

在 TypeScript 中,interfacetype 都可以用来定义对象的结构。它们之间有一些细微的差别:

interface是接口,type是类型,本身就是两个概念。只是碰巧表现上比较相似。 希望定义一个变量类型,就用type,如果希望是能够继承并约束的,就用interface。 如果你不知道该用哪个,说明你只是想定义一个类型而非接口,所以应该用type

讨论链接