likes
comments
collection
share

探寻TS中那些你不知道的工具类

作者站长头像
站长
· 阅读数 10

探寻TS中那些你不知道的工具类

前言

作为一个资深前端螺丝工,我总是在思考一个问题:“如何拧螺丝拧的更帅气,拧出满满的技术感?”。单个项目高大上,那是是帅一次,可我想帅一辈子 <手动狗头> 那如何在所有项目里都拧的好,拧的帅,拧的高大上呢? --Typescript 应运而生

面对下面三个经典的灵魂拷问:

  • 你是否还在使用 “anyscript”?(yes)
  • 你是否特别想拒绝any却又不知如何下手?(yes)
  • 你是否创建着ts文件却还在干着js的事?(yes) 我已经帮大家回答好了。相信大家已经受够了anyscript,受够了代码里any遍地开花的情景,受够了代码太low,没法装B的事实。那么这里我将从实际应用出发不谈原理不谈实现只谈使用,持续更新经常用到的TS知识小Tip。原理啥的后续再说。(起码要等我学会了再装B

今天主要带来的是TS的工具类。什么是工具类,简单的说,就是TS已经用范型写好了的支持面向类型编辑的api。这些工具类能够帮我们轻松完成复杂类型的转换 或 避免自己开发写一大堆范型进行不确定的类型兼容。

Partail

interface Animal { name: string;  age: number; }
// 或 type Animal = { name: string; age: number } 也可
type Dog = Partail<Animal>
// type Dog = { name?: string | undefined ; age?: number | undefined; }
// 顾名思义,type B 是 type A的所有属性转换为可选属性的集合
const dog: Dog = { age: 1 }

Required 和Partail相反

type Animal = { name?: string; age: number;}
type Cat = Required<Animal>
// type Cat = { name: string;  age: number; }
// 顾名思义,type B 是 type A的所有属性转换为必须属性的集合
const cat: Cat = { name: 'cat-halo'; age: 2; }

Readonly

type Animal = { name?: string; age: number;}
type Dog = Readonly<Animal>
// type Dog = { readonly name: string; readonly age: number; }
// 顾名思义,type B 是 type A的所有属性转换为只读属性的集合,不能新增,不能减少,不能改变
const dog: Dog = { name: 'cat-halo'; age: 2; }

Record<K,T>

type Animal = { name: string; age?: number; }
type Proper = "cat" | "dog"
type SingleAnimal = Record<Proper, Animal>
// type SingleAnimal = { cat: { name: string }; dog: { name: string; age:number } }
// 顾名思义,Record<K, T>是key为K,value为T 的对象的集合

Exclude<UnionType,ExcludeType>

type Animal = Exclude<string | number | boolean, string | boolean>
// type Animal = number
// 顾名思义, 就是除去ExcludeType,返回剩余类型的集合

Extract<T,Union>

type Animal = Extract<string | number | boolean | ()=> void, Function | boolean>
// type Animal = boolean | ()=> void
// 顾名思义, 就是取 T和Union的交集

Pick<T,K>

type Animal = {
    name: string;
    age: number;
}
type Dog = Pick<Animal, "name">
// type Dog = { name: string }
// 顾名思义, 从T里挑选K 返回集合

Omit<T,K>

type Animal = { name: string; age?: number; }
type Dog = Omit<Animal, "age" | "sex">
// type Dog = { name: string }
// 顾名思义, 从T中删除K, 返回剩余类型的集合

NonNullable

type Animal = string | number | ()=> void | null | undefined;
type Dog = NonNullable<Animal>
// type Dog = string | number | ()=> void;
// 顾名思义, 去除null 和 undefined

ReturnType

type Dog = ReturnType<()=> void> // void
type Cat = ReturnType<<T>()=> T> // unknown
type Bird = ReturnType<()=> { name: string }> // { name: string }
// 顾名思义, 返回函数结果的类型集合

InstanceType

class Animal{
    name: '',
    age: ''
}
const dog: InstanceType<typeof Animal> = new Animal()
// 顾名思义, 返回类的类型,约束类创建的实例

Parameters 用的少

后续

将会持续进行TS方面的精进并更多分享关于TS使用的技巧,与广大资深攻城狮共同进步。 同时感谢文章Conditional Types in TypeScript的范型理解帮助。