gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:59:37 25 4
gpt4 key购买 nike

我可以用接口(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com