TypeScript: interfaces 与 type 的区别和相同点

前端人

共 4794字,需浏览 10分钟

 · 2021-08-17

鬼哥本周将通过几篇优秀的Typescript文章,让大家学习到Typescript一些高级的用法,让大家对Typescript更加的深入理解,并且更好实践到工作当中,【一共七篇文章】,关注我们一起完成这个系列的学习

原文:https://github.com/leslie1943




🚀🚀 1. Objects / Functions

  • 接口和类型别名都可以用来描述对象的形状或函数签名
  • 使用接口定义
// 使用接口
interface Point{
    x: number
    y: number
}

interface SetPoint {
    (x:number, y:number): void
}
  • 使用类型别名定义
type Point = {
    x: number
    y: number
}

type SetPoint = (x: number, y: number) => void;

🚀🚀 2. Other Types

  • 与接口类型不同, 类型别名可以用于一些其他类型, 比如原始类型, 联合类型和元组
 // 原始类型
 type Name = string

 // const name: Name = 22
 const name: Name = 'sss'

 // Object
 type PartialPointX = { x: number }
 type PartialPointY = { y: number; z: number }

 // Union Object
 type PartialPoint = PartialPointX | PartialPointY
 const pointx: PartialPointX = { x: 1 }
 const pointy: PartialPointY = { y: 1, z: 88 }
 const pointer: PartialPoint = { x: 100, y: 200, z: 300 }

 // Tuple
 type Data = [numberstring]
 const dataArr: Array<Data> = [[1'ss']]
 const data: Data = [1'ss']

🚀🚀 3 Extend

  • 接口和类型别名都能够被扩展, 但语法有所不同. 此外, 接口和类型别名不是互斥的.
  • ✅ 接口可以扩展类型别名
  • ❌ 类型别名不能扩展接口

🎃interface extends interface

  interface PartialPointX {
      x: number
  }
  interface Point extends PartialPointX {
      y: number
  }
  const point: Point = { x: 11, y: 22 }

🎃Type Alias extends type alias

  type FirstName = { first: string }

  type FullName = FirstName & { last: string }

  const fullName: FullName = { first: 'su', last: 'zhen

🎃interface extends type alias

 type PartialPointX = {
     x: number
 }

 interface Point extends PartialPointX {
     y: number
 }

 const point: Point = {
     x: 1,
     y: 2,
 }

🎃type alias extends interface

 interface FirstName {
     first: string
 }

 type FullName = FirstName & { last: string }
     const name: FullName = {
     first: 'su',
     last: 'zhen',
 }
  • 接口扩展的时候使用 extends
  • 类型别名扩展的时候使用 &

🚀🚀 4 Implements

  • 类可以以相同的方式实现接口或类型别名 ✅✅✅
  • 但类不能实现使用类型别名定义的联合类型 ❌❌❌
interface Point {
  x: number
  y: number
}

class SomePoint implements Point {
  x = 0
  y = 0
}

type Point2 = {
  x: number
  y: number
}

class SomePoint2 implements Point2 {
  x = 0
  y = 0
}

type PartialPoint = { x: number } & { y: number }
// A class can only implement an object type or
// intersection of object types with statically known members.ts(2422)
// class SomePartialPoint implements PartialPoint {} // Error ❌

🚀🚀 5 Declaration merge

接口可以定义多次, 自动合并到单个接口中

interface Point {
  x: number
}

interface Point {
  y: number
}

interface Point {
  y: number
}

interface Point {
  z: number
}

const point: Point = {
  x: 1,
  y: 2,
  z: 3,
}
  • 类型别名只允许定义一次
type Name = {
  first: string
}

type Name = {
  last: string
}
Duplicate identifier 'Name'.ts(2300)

关注公众号添加鬼哥微信,和鬼哥一起学习

❤️ 看完三件事

如果你觉得这篇内容对你挺有启发,不妨:

  • 点个【在看】,或者分享转发,让更多的人也能看到这篇内容

  • 点击↓面关注我们,一起学前端

  • 长按↓面二维码,添加鬼哥微信,一起学前端



浏览 46
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报