typescript - 接口(interface)和类型别名之间有语义差异吗?

标签 typescript

我可以用接口(interface)和类型别名做大部分相同的事情。

例如

类可以实现接口(interface)或类型别名

interface Shape {
    area(): number;
}

type Perimeter = {
    perimeter(): number;
}

class Rectangle implements Shape, Perimeter {
}

它们可以组合起来创建新的接口(interface)/类型别名

interface A {
    a: string;
}

type B = {
    b: string
}

interface C extends B {
    c: string;
}

type D = A & {
    d: string;
}

接口(interface)和类型注释之间是否存在语义差异?

最佳答案

interfacetype 之间存在技术差异,即 well-described here .

但是,对于typeinterface都可以使用的情况,根本没有语义上的区别。

关于TypeScript中的interface继承和type交集

在 TypeScript 中,接口(interface)之间的层次结构只是一种定义接口(interface)的方式。但是一旦它们被定义,接口(interface)之间就没有真正的父子关系了。例如:

interface Named {
    name: string
}
interface Person extends Named {
    age: number
}
interface Animal {
    name: string
    age: number
}

这里 PersonAnimal 是同一类型。一旦它们被定义,当其他代码使用它们时,编译器将以完全相同的方式处理它们:

function useNamed(named: Named) {
}
let p: Person = /* ... */
let a: Animal = /* ... */
useNamed(p) // OK
useNamed(a) // also OK, because if 'Animal' is compatible with
            // `Named` then it is a `Named`

这就是为什么同样的类型也可以使用交集类型来创建:

type Engine = Named & {
    age: number
}

来自规范:

Intersection types represent values that simultaneously have multiple types. A value of an intersection type A & B is a value that is both of type A and type B. (source: TypeScript Specification)

我们的 Engine 类型既是 Named 又是附加定义:它在语义上与接口(interface)继承相同。而这里的Engine类型与PersonAnimal完全相同。

关于typescript - 接口(interface)和类型别名之间有语义差异吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54536133/

相关文章:

typescript - 是否可以根据数组值强类型化对象的键?

javascript - 在 Vue 应用程序中模拟 axios 以进行前端测试

typescript - 绕过 tslint : one-variable-per-declaration

angular - array.push() 制作的数组有元素但不能使用 angular

javascript - 如何在 typescript 声明文件中定义单例 javascript 类

html - 在图库中使用虚拟滚动

typescript - 类型错误 : Property 'currentTime' does not exist on type 'EventTarget & HTMLInputElement'

angular - 在测验中处理多个单选按钮并且还面临找不到路径为 : 的控件

reactjs - 使用 React 和 TypeScript 时如何正确输入 @connect?

javascript - 如何在单独的项目中使用自动生成的 typescript 声明文件?