TypeScript笔记 —— 类型别名

162 阅读2分钟

类型别名

在前面,我们通过在类型注解中编写 对象类型 和 联合类型,但是当我们想要多次在其他地方使用时,就要编写多次。我们可以给对象类型起一个别名。

type Point = {
    x: number
    y: number
}

function printPoint(point: Point) {
    console.log(point.x, point.y)
}

function sumPoint(point: Point) {
    console.log(point.x + point.y)
}

printPoint({x: 20, y: 30})
sumPoint({x: 20, y:30})
type ID = number | string
function printId(id: ID) {
    console.log(id)
}

接口的声明

在前面我们通过type可以用来声明一个对象类型。

type Point = {
    x: number
    y: number
}

对象的另外一种声明方式就是通过接口来声明。

interface Point {
    x: number
    y: number
}

那么它们有什么区别呢?类型别名和接口非常相似,在定义对象类型时,大部分时候,你可以任意选择使用。接口的几乎所有特性都可以在 type 中使用。

interface和type区别

我们会发现interface和type都可以用来定义对象类型,那么在开发中定义对象类型时,到底选择哪一个呢?如果是定义非对象类型,通常推荐使用type,比如Direction、Alignment、一些Function。

如果是定义对象类型,那么他们是有区别的:

  • interface 可以重复的对某个接口来定义属性和方法
  • 而type定义的是别名,别名是不能重复的
interface IPerson {
    name: string
    running: () => void
}

interface IPerson {
    age: number
}

image.png 所以,interface可以为现有的接口提供更多的扩展。

交叉类型

前面我们学习了联合类型,联合类型表示多个类型中一个即可。

type Alignment = 'left' | 'right' | 'center'

还有另外一种类型合并,就是交叉类型。交叉类似表示需要满足多个类型的条件,交叉类型使用 & 符号。

我们来看下面的交叉类型。

type MyType = number & string

表达的含义是number和string要同时满足。但是有同时满足是一个number又是一个string的值吗?其实是没有的,所以MyType其实是一个never类型。

所以,在开发中,我们进行交叉时,通常是对对象类型进行交叉的。

interface Colorful {
    color: string
}

interface IRun {
    running: () => void
}

type NewType = Colorful & IRun

const obj: NewType = {
    color: 'red',
    running: function() {}
}