在 TypeScript 中,接口(interface
)和类(class
)都可以用来定义类型,但它们的使用场景和目的有所不同。选择使用接口还是类,取决于你的具体需求。以下是一些指导原则,帮助你决定何时使用接口,何时使用类。
interface
)接口主要用于定义对象的形状(shape),即对象应该有哪些属性和方法。接口是纯类型定义,不会生成任何 JavaScript 代码。
interface User {
id: number;
name: string;
email: string;
}
function printUser(user: User) {
console.log(`User: ${user.name}, Email: ${user.email}`);
}
class
)类不仅定义了对象的形状,还提供了实现。类可以包含属性和方法的实现,并且可以被实例化。
public
、private
、protected
等访问修饰符,可以控制属性和方法的访问权限。class User {
id: number;
name: string;
email: string;
constructor(id: number, name: string, email: string) {
this.id = id;
this.name = name;
this.email = email;
}
print() {
console.log(`User: ${this.name}, Email: ${this.email}`);
}
}
const user = new User(1, "John Doe", "john.doe@example.com");
user.print();
在实际开发中,接口和类经常结合使用。你可以使用接口来定义类的结构,然后让类实现这个接口。
interface IUser {
id: number;
name: string;
email: string;
print(): void;
}
class User implements IUser {
id: number;
name: string;
email: string;
constructor(id: number, name: string, email: string) {
this.id = id;
this.name = name;
this.email = email;
}
print() {
console.log(`User: ${this.name}, Email: ${this.email}`);
}
}
const user = new User(1, "John Doe", "john.doe@example.com");
user.print();
根据你的具体需求,选择合适的工具来定义类型。