7个你必须知晓的TypeScript里的方式

lxf2023-03-12 11:56:01

本文跟大家分享7个你必须知晓的TypeScript里的方式,希望能帮助到大家!

7个你必须知晓的TypeScript里的方式

TypeScript 里的类型系统是非常强大的。它为我们提供了类型安全。类型系统尽管招人喜爱,但如果我们不计划和设计类型和插口,它还会使我们编码越来越错乱难懂。

泛型

防止编码反复中,建立可器重的种类,就是我们撰写简约编码重要的一环。泛型是 TypeScript 的一个作用,它容许大家撰写可器重的种类。看看下面的事例:

type Add<T> = (a: T, b: T) => T

const addNumbers: Add<number> = (a, b) => {
  return a   b
}

const addStrings: Add<string> = (a, b) => {
  return a   b
}

将正确种类放进Add的泛型中,它能够被用于叙述数字的求和或多个字符串数组连接。并不需要为每一个函数公式写一个种类,而只需要用泛型做一次。这不但节约了我们时间精力,并且让我们的编码更为简约,也不易出差错。

好用种类

TypeScript 原生态带来了好多个有价值的好用种类来帮助我们开展一些常见的数据转换。这种好用类型是全局性可利用的,他们都使用了泛型。

以下这7个是我经经常使用的。

1. Pick<Type, Keys>

Pick是从 Type 中选择特性集 Keys 来建立一个新的种类,Keys 能够是一个字符串数组字面上或字符串数组字面上的联合。Keys 数值一定要 Type 的键,不然TypeScript编译程序会埋怨。当你要根据从有许多属性目标中选择一些特性来建立更较轻目标时,这一好用种类尤其有效。

type User = {
  name: string
  age: number
  address: string
  occupation: string
}

type BasicUser = Pick<User, "name" | "age">

// type BasicUser = {
//   name: string;
//   age: number;
// }

2. Omit<Type, Keys>

OmitPick反过来。 Keys 并不是说是要保存什么特性,反而是指得省去的特性键集。 在我们只想要从目标中删掉一些特性并保留别的特性时,这一会很有用。

type User = {
  name: string
  age: number
  address: string
  occupation: string
}

type BasicUser = Omit<User, "address" | "occupation">

// type BasicUser = {
//   name: string;
//   age: number;
// }

3. Partial<Type>

Partial 结构了一个种类,其每一个种类特性都设为可选择。我们在撰写一个对象的更新逻辑性时,这个可能非常有利。

type User = {
  name: string
  age: number
  address: string
  occupation: string
}

type PartialUser = Partial<User>

// type PartialUser = {
//   name?: string;
//   age?: number;
//   address?: string;
//   occupation?: string;
// }

4. Required<Type>

RequiredPartial反过来。它结构了一个类别的全属性全是必录的种类。它能够被用于保证在一个类型中并没有可选择特性发生。

type PartialUser = {
  name: string
  age: number
  address?: string
  occupation?: string
}

type User = Required<PartialUser>

// type User = {
//   name: string;
//   age: number;
//   address: string;
//   occupation: string;
// }

5. Readonly<Type>

Readonly 构建了一个种类,其类别的全属性被设为写保护。分配一个新的值 TS 便会出错。

type User = {
  name: string
  age: number
  address: string
  occupation: string
}

type ReadOnlyUser = Readonly<User>

const user: ReadOnlyUser = {
  name: "小编",
  age: 24,
  address: "厦门市",
  occupation: "大迁全球"
}

user.name = "王大冶"
// Cannot assign to 'name' because it is a read-only property.

6. ReturnType<Type>

ReturnType 从一个函数类型的返回类型构建一个种类。在我们解决来源于外界库的函数类型同时也希望根据他们创建自定义类型时,这是非常有利的。

import axios from 'axios'

type Response = ReturnType<typeof axios>

function callAPI(): Response{
  return axios("url")
}

除开前面提到的,还有其他的好用种类能帮助我们撰写很干净编码。有关常用工具类别的TypeScript文档链接能够找到属于自己的。

https://www.typescriptlang.org/docs/handbook/utility-types.html

好用类型是TypeScript所提供的非常有利的功效。开发者应当运用他们来预防硬编码种类。会比朋友更秀? 这些都是我们需要知晓的!

文中转截在:https://segmentfault.com/a/1190000040574488

大量程序编写基本知识,请访问:编程学习!!

以上就是关于探讨TypeScript中非常值得知道的7种方法的具体内容,大量欢迎关注AdminJS其他类似文章!