在TypeScript中,interface
?和?type
?是用于定义类型的两种主要方式,它们有一些相似之处,但也存在一些关键的区别。
定义类型:?无论是interface
还是type
,都可以用来定义对象、函数、类等的类型。
可扩展性:?你可以通过扩展已存在的interface
或type
来添加新的成员。
1、可声明的合并:
interface
支持声明合并。这意味着如果你定义了两个相同名称的interface
,它们会被合并成一个。
type
也支持声明合并,但只有在定义对象类型时才会发生,而不是在定义交叉类型(&
)或联合类型(|
)时。
//?interface?的声明合并
interface?Car?{
????brand:?string;
}
interface?Car?{
????model:?string;
}
//?合并后的结果
/*
interface?Car?{
????brand:?string;
????model:?string;
}
*/
//?type?的声明合并(只在对象类型时发生)
type?Person?=?{
????name:?string;
};
type?Person?=?{
????age:?number;
};
//?合并后的结果
/*
type?Person?=?{
????name:?string;
????age:?number;
}
*/
2、支持联合类型和交叉类型:
type
支持联合类型和交叉类型的定义,而interface
主要用于对象类型的定义。
//?使用?type?定义联合类型
type?ID?=?string?|?number;
//?使用?type?定义交叉类型
type?Address?=?{
????city:?string;
}?&?{
????country:?string;
};
//?interface?不能直接定义联合类型或交叉类型
3、兼容性检查:
interface
更严格,进行属性检查时要求实现对象具有接口中定义的所有属性。
type
则相对宽松,只要实现对象具有类型中的一部分属性即可。
//?interface?的属性检查
interface?Point?{
????x:?number;
????y:?number;
}
//?错误,缺少?y?属性
const?point:?Point?=?{?x:?0?};
//?type?不进行属性检查
type?Coordinates?=?{
????x:?number;
????y:?number;
};
//?正确,type?不会报错
const?coords:?Coordinates?=?{?x:?0?};
总体而言,选择使用interface
还是type
通常取决于你的具体需求。如果你主要在定义对象类型时,并且需要声明合并、严格属性检查,那么使用interface
可能更合适。如果你需要更灵活的类型定义,比如联合类型、交叉类型,或者在一些其他场景下,那么使用type
可能更适合。