获得徽章 20
赞了这篇文章
#每天一个知识点#
// 在 TypeScript 中,type 和 interface 主要的区别在于它们的扩展(extends)和实现(implements)。
// Interface
interface InterfaceExample {
name: string;
age: number;
}
// Type
type TypeExample = {
name: string;
age: number;
};
// Interface 可以通过 extends 关键字进行扩展
interface ExtendedInterfaceExample extends InterfaceExample {
gender: string;
}
// Type 可以通过交叉类型进行扩展
type ExtendedTypeExample = TypeExample & {
gender: string;
};
// 类可以实现(implements)接口
class ClassExample implements InterfaceExample {
name: string;
age: number;
}
// 但是类不能实现(implements)类型
// 下面的代码会报错
// class ClassExample2 implements TypeExample {
// name: string;
// age: number;
// }
// 在 TypeScript 中,type 和 interface 主要的区别在于它们的扩展(extends)和实现(implements)。
// Interface
interface InterfaceExample {
name: string;
age: number;
}
// Type
type TypeExample = {
name: string;
age: number;
};
// Interface 可以通过 extends 关键字进行扩展
interface ExtendedInterfaceExample extends InterfaceExample {
gender: string;
}
// Type 可以通过交叉类型进行扩展
type ExtendedTypeExample = TypeExample & {
gender: string;
};
// 类可以实现(implements)接口
class ClassExample implements InterfaceExample {
name: string;
age: number;
}
// 但是类不能实现(implements)类型
// 下面的代码会报错
// class ClassExample2 implements TypeExample {
// name: string;
// age: number;
// }
展开
评论
点赞