Typescript基础4

173 阅读3分钟

本文已参与「新人创作礼」活动, 一起开启掘金创作之路。

这是typescript学习的系列课程,今天开启typescript的第4篇。

不多说废话,直接精简出最精华的部分给大家。

如果有朋友对于typescript的基础不是很了解的话,欢迎点击下面两篇文章跳转进行学习。

接前面三篇:

接下来我们看学习一些稍微复杂的知识。

交叉类型

交叉类型更像是类型之间的一个合并。 举个例子:

interface IpersonType = {
	name: string;
	age: number;
}

interface IhobbyType = {
	name: string;
	hobby: string[];
}

type ImergeType = IpersonType & IhobbyType;

const myInfo = {
	name: 20,
	age: 30hobby: ['篮球''足球', '排球']
}

通过测试。

类型断言

类型断言的规则: 断言只能断言成更加具体的类型, 或者 不太具体(any/unknown) 类型。

一般使用关键字as。

举个例子:

const imgElement = document.querySelector(".myImg") as HTMLImageElement
imgElement.src = "xxx"
imgElement.alt = "yyy"

上面的例子表示当前的类型为图片节点类型,给这个类型下一个断言。

以上是基本类型的断言,下面将一种特殊的类型断言:非空类型断言。

非空类型断言

非空类型断言一般是使用叹号!表示的。

如下所示: 比如定义下面这样的类型格式,属性hobby不确定是否存在,那么我们在使用的时候,可以用非空类型断言和缩小范围的方式,但是非空类型断言会有点危险, 只有确保myhobby一定有值的情况, 才能使用。

interface IPerson {
  name: string
  age: number
  myhobby?: {
    name: string
  }
}

const info: IPerson = {
  name: "why",
  age: 18
}

// 解决方案一: 类型缩小
if (info.myhobby) {
  info.myhobby.name = "唱歌"
}

// 解决方案二: 非空类型断言(有点危险, 只有确保friend一定有值的情况, 才能使用)
info.myhobby!.name = "跳舞"

通过上面两个例子可以看出来,对类型断言的使用。

字面量类型

举例几个字面量类型的例子,这个在我们的日常工作中用的比较多。

// 1.字面量类型的基本使用
const name: "why" = "why"
let age: 18 = 18

// 2.将多个字面量类型联合起来 |
type Direction = "left" | "right" | "up" | "down"
const d1: Direction = "left"

// 栗子: 封装请求方法
type MethodType = "get" | "post"
function request(url: string, method: MethodType) {
}

request("http://www.baiduapiPost.cn", "post");

类型缩小的使用

这种情况一般会针对联合类型用的比较多一些。例如在联合类型中定义几种情况,通过缩小范围的方式针对具体的情况做逻辑处理。

例子如下:

// 1.typeof: 使用的最多
function printIdResult(id: number | string) {
  if (typeof id === "string") {
    console.log(id.length)
  } else {
    console.log(id)
  }
}


// 2.方向的类型判断
type Direction = "left" | "right" | "up" | "down"
function showDirection(direction: Direction) {
  if (direction === "left") {
    console.log("向左移动");
  } else if (direction === "right") {
    console.log("向右移动");
  } else if (direction === "up") {
    console.log("向上移动");
  } else if (direction === "down") {
    console.log("向下移动");
  }
}

// 3. instanceof: 传入一个日期, 打印日期
function printDate(date: string | Date) {
  if (date instanceof Date) {
    console.log(date.getTime())
  } else {
    console.log(date)
  }
}

// 4.in: 判断是否有某一个属性
interface ISwim {
  swim: () => void
}
interface IRun {
  run: () => void
}
function move(animal: ISwim | IRun) {
  if ("swim" in animal) {
    animal.swim()
  } else if ("run" in animal) {
    animal.run()
  }
}

ok,以上为今天对于交叉类型、类型断言、字面量类型等知识的分享。

学如逆水行舟,不进则退。第一天不求贪多,只求稳步的进步。