typescript - 接口和类型别名之间是否存在语义差异?
问题描述
我可以用接口和类型别名做大部分相同的事情。
例如
类可以实现接口或类型别名
interface Shape {
area(): number;
}
type Perimeter = {
perimeter(): number;
}
class Rectangle implements Shape, Perimeter {
}
它们可以组合起来创建新的接口/类型别名
interface A {
a: string;
}
type B = {
b: string
}
interface C extends B {
c: string;
}
type D = A & {
d: string;
}
接口和类型注释之间是否存在语义差异?
解决方案
接口可以扩展其他接口,也可以*实现类。接口也可以利用声明合并:
type A = {
a: string;
}
type A = { // <-- error: duplicate identifier A
b: string;
}
interface A {
a: string;
}
interface A { // <-- okay, A is { a: string, b: string }
b: string;
}
编辑:更改为 *implement
编辑2:交叉点与延伸不同。考虑以下:
interface A {
num: number;
str: string;
}
type B = A & { // <-- this is okay, but overwrites the num property type to number & string
arr: any[];
num: string;
}
interface C extends A { // <-- error: C incorrectly extends A
num: string;
}
编辑 3:对于某些人来说,另一个潜在的显着差异(尽管不一定是语义差异)是类型在工具提示中枚举(至少在 vscode 中),但接口不是。
推荐阅读
- python - 如何 4 路匹配 Excel 中不同工作表中的子集字符串列(Google 表格、Python、R 答案也可以)
- jquery - jQuery img alt 属性末尾带有变量
- git - Gitlab ssh 已启用但不再允许克隆/推送/等
- reactjs - 将 React 门户直接附加到 DOM 节点与分离节点之间的区别?
- java - 生命周期配置未涵盖插件执行 - Linux Maven
- redux - 使用 Redux Store 作为全局状态的 React 组件可重用性问题
- vb.net - Crystal Reports - 将两个数值字段值与公式进行比较
- powershell - 如何在另一个 powershell 脚本中包含另一个 powershell 脚本文件?
- javascript - JavaScript - 我的复选框(默认选中)不会在页面加载时运行它的脚本
- python - 有没有更快的方法来汇总 Xarray 数据集变量?