我可以用接口(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)和类型注释之间是否存在语义差异?
最佳答案
interface
和 type
之间存在技术差异,即 well-described here .
但是,对于type
和interface
都可以使用的情况,根本没有语义上的区别。
关于TypeScript中的interface
继承和type
交集
在 TypeScript 中,接口(interface)之间的层次结构只是一种定义接口(interface)的方式。但是一旦它们被定义,接口(interface)之间就没有真正的父子关系了。例如:
interface Named {
name: string
}
interface Person extends Named {
age: number
}
interface Animal {
name: string
age: number
}
这里 Person
和 Animal
是同一类型。一旦它们被定义,当其他代码使用它们时,编译器将以完全相同的方式处理它们:
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
类型与Person
和Animal
完全相同。
关于typescript - 接口(interface)和类型别名之间有语义差异吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54536133/