代码编织梦想

TypeScript 常用的工具类型

总结了常用的工具类型

用TS保证类型安全

Awaited<Type>

获取Promise中的结果类型

ReturnType<Type>

获取函数的返回值类型. 用ReturnType

// 获取Func 类型的返回值类型
type Func = (value:string)=> string;
// 约束变量u的类型为`函数的返回值`类型
const u:ReturnType<Func> ="1";

Parameters<Type>

获取函数的参数类型,将每个参数类型放进一个元组中。 用Parametes

type U = Parameters<(a:number, b:string)=> void>;// [number, string]

NonNullable<Type>

去除类型中的null,和undefined

// 用NonNullable去除类型中的null, 和undefined类型
type U = NonNullable<string[]|null|undefined>; // string[]

Omit<Type, Keys>

省略

移除一些属性, 用Omit,Omit<T, K>从T中取出除去K的其他所有属性

本质上是Pick的反向操作,排除掉Keys。

type Test = {
  name: string;
  age: number;
  salary?: number;
};
type omitted = Omit<Test, "age">;
// 结果
// type omitted = {
//     name: string;
//     salary?: number;
// }

// 将其赋值给omitted对象
const omitted:Omitted = {
    name: 'zhangsan',
    salary:29
}

Pick<Type, Keys>

选择

从Type中选取一系列的属性, 用Pick, 构成新的类型

type Test = {
  name: string;
  age: number;
  salary?: number;
};

//pick
type Picked = Pick<Test, "name" | "age">;
// 结果
// type Picked = {
//     name: string;
//     age: number;
// }

// 将其赋值给pick对象
const pick:Picked = {
    name: 'zhangsan',
    age:29
}
type Pick<T, K extends keyof T> = {
    [P in K]: T[P]
};

Exclude<T, U>

移除

移除联合类型中的某些类型, 用Exclude<T, U>.表示从T中移除出U

type U1 = Exclude<"string"|"number"|"boolean","string">; // "number"|"boolean"

Extract<T, U>

抽取

提取联合类型中的某些类型, 用Extract<T, U>.表示从T中提取出U

type U = Extract<string | number|(()=>void), Function>; // ()=>void

Extract 提取联合类型中的函数类型,得到()=>void

1. 用于基础类型

type base1 = Extract<string | number, string>; //string || never; //实测是string
type base2 = Extract<string, string | number>; //string

2. 用于函数

type func1 = (one: number, two: string) => string;
type func2 = (one: number) => string;

//  参数少的函数类型 extends 参数多的函数类型 返回true
//  参数多的函数类型 extends 参数少的函数类型 返回false
type beginType1 = func1 extends func2 ? func1 : never; //never
type beginType2 = func2 extends func1 ? func2 : never; //func2

//这个Extract是TS内置方法
type tType1 = Extract<func1, func2>; //never
type tType2 = Extract<func2, func1>; //= (one: number) => string  和上面有区别

3.Extract 用于类

class People {
  public name!: string;
  public age!: number;
  public address!: string;
  eat() {}
}

class CnPeople extends People {
  private phone!: string;
}

let cp = new CnPeople();

// 现在这个Extractxx是自定义的,不是内置。但功效和内置的Extract一样
type Extractxx<T, U> = T extends U ? T : never;

// 定律1:子类 extends 父类; 永远true,返回T类型
type extractType = Extractxx<CnPeople, People>; // CnPeople

// 定律: 父类 extends 子类; 只有实例属性或实例方法一样时则为true
type extractType2 = Extractxx<People, CnPeople>; // never 

4. Exclude 刚好和 Extract 相反

type ec1 = Exclude<func1, func2>; //(one: number, two: string) => string;
type ec2 = Exclude<string, string | number>; //never

Partial

将类型的所有属性变为可选属性, 用Partial

interface User{
    name:string;
    age:number;
}

const u:User= {  // X, 类型缺失, 报错
    name:'zhangsan'
}


const u:Partial<User> = { // 使用Partial,将所有类型变为可选后,不报错. 可赋值给变量u使用
    name:'zhangsan'
}
type Partial<T> = {
    [P in keyof T]?: T[P]
};

Required

将类型的所有属性变为必选,用Required属性

interface User{
    name?: string;
    age?: number;
    gender?: string[]

const u:Required<User> = {
    name:'zhangsan',
    age:18,
    gender:["male"]
}

Required<User>处理后的属性,直接赋值给变量u. 变量u的所有属性都是必选

type Required<T> = {
    [P in keyof T]-?: T[P]
};

Readonly

将数组或对象的属性值转换为只读的,用Readonly

interface User {
    name: string;
    age: number;
    gender?: 'male'|'female'
}
 
let u: Readonly<User> = {
   name: "hello",
   age: 10,
   gender: 'male'
}
u.age = 190   // X, 用Readonly 包裹的接口,各属性是只读的. 将其指定为变量类型.  
              // 变量赋值报错

Record

解释1: 将对象所有属性的值转化为T类型, 用Record<K extends keyof any,T>

解释2: 快速生成某种属性的K类型

解释3: Record<K,T>构造具有给定类型T的一组属性K的类型。在将一个类型的属性映射到另一个类型的属性时,Record非常方便。

解释4: 将一个类型的所有属性值都映射到另一个类型上并创造一个新的类型.

例子1:

type Property = 'use1'|'use2'
type User = Record<Property, string>

const u: User = {
    use1:'xiaoxue',
    use2:'zhangsan'
}

将生成的User类型赋值给u使用

例子2:

type HD = Record<string, string|name>
const hd:HD = {name:'zhangsan',age:28, address:'abc'}

例子3:

interface EmployeeType {
    id: number;
    fullname: string;
    role: string;
}
 
let employees: Record<number, EmployeeType> = {
    0: { id: 1, fullname: "John Doe", role: "Designer" },
    1: { id: 2, fullname: "Ibrahima Fall", role: "Developer" },
    2: { id: 3, fullname: "Sara Duckson", role: "Developer" },
}
 
// 0: { id: 1, fullname: "John Doe", role: "Designer" },
// 1: { id: 2, fullname: "Ibrahima Fall", role: "Developer" },
// 2: { id: 3, fullname: "Sara Duckson", role: "Developer" }

Record的工作方式相对简单。在这里,它期望数字作为类型,属性值的类型是EmployeeType,因此具有idfullNamerole字段的对象。

源码

/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};

常用的格式

type proxyKType = Record<K,T>

这里会将K中的所有属性值都转换为T类型,并将返回的新类型返回给proxyKType,K可以是联合类型、对象、枚举….

//demo1
type petsGroup = 'dog' | 'cat' | 'fish';
interface IPetInfo {
    name:string,
    age:number,
}

type IPets = Record<petsGroup, IPetInfo>;

const animalsInfo:IPets = {
    dog:{
        name:'dogName',
        age:2
    },
    cat:{
        name:'catName',
        age:3
    },
    fish:{
        name:'fishName',
        age:5
    }
}

可以看到 IPets 类型是由 Record<petsGroup, IPetInfo>返回的。将petsGroup中的每个值(‘dog’ | ‘cat’ | ‘fish’)都转为 IPetInfo 类型。

当然也可以自己在第一个参数后追加额外的值,如下面:

//demo2
type petsGroup = 'dog' | 'cat' | 'fish';
interface IPetInfo {
    name:string,
    age:number,
}

type IPets = Record<petsGroup | 'otherAnamial', IPetInfo>;

const animalsInfo:IPets = {
    dog:{
        name:'dogName',
        age:2
    },
    cat:{
        name:'catName',
        age:3
    },
    fish:{
        name:'fishName',
        age:5
    },
    otherAnamial:{
        name:'otherAnamialName',
        age:10
    }
}

可以看到在demo1的基础上,demo2在

type IPets = Record<petsGroup | ‘otherAnamial’, IPetInfo>; 中除了petsGroup的值之外,还追加了 'otherAnamial’这个值。

https://www.bilibili.com/video/BV1gL411Y7Mf/?spm_id_from=333.337.search-card.all.click&vd_source=631062e9ff21033189723c8ac931c360

下一节:

手写工具类型

https://www.bilibili.com/video/BV1Lv4y1H7SK/?spm_id_from=333.337.search-card.all.click&vd_source=631062e9ff21033189723c8ac931c360

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_35812380/article/details/131027845

TypeScript常用工具泛型函数总结-爱代码爱编程

最近用到了TS中一些工具泛型,觉得TS中的很多工具泛型函数用处还是很大的,在这里总结一些常用的: Partial Partial的作用是将传入的属性变成可选项,原理就是使用keyof拿到所有属性名,然后再使用in遍历,T[P]拿到相应的值。Required Required 的作用是将传入的属性变为必选项,原理是使用-?将可选项的?去掉。与之对应的还有个

TypeScript 常用类型-爱代码爱编程

TypeScript 从编程语言的动静来区分,TypeScript 属于静态类型的编程语言,JS 属于动态类型的编程语言。 静态类型:编译期做类型检查; 动态类型:执行期做类型检查。 代码编译和代码执行的顺序:1 编译 2 执行。 TypeScript 初始化 1 安装编译 TS 的工具包 问题:为什么要安

一文讲解Ts中工具类型-爱代码爱编程

开篇  对于Ts的工具类型,在使用第三方工具时,会看到其源码库用到工具类型的频率会非常高,对于初入Ts的同学,真的会看的一脸懵,工具类型的使用会有利于我们所编写组件库中类型的封装,避免类型重复的进行声明定义,大大提高了我们的开发效率与规范性。下面我将为大家介绍Ts中以下工具类型的应用keyof、extends、typeof、Partial、Record、

【typescript】掌握 typescript 这些官方工具类型_吉帅振的网络日志的博客-爱代码爱编程

自我介绍:大家好,我是吉帅振的网络日志(其他平台账号名字相同),互联网前端开发工程师,工作5年,去过上海和北京,经历创业公司,加入过阿里本地生活团队,现在郑州北游教育从事编程培训。 一、前言 在 TypeScript 中

typescript 实用工具类型之 pick 类型_夏安   的博客-爱代码爱编程

TypeScript 实用工具类型之 Pick 类型 TypeScript 实用工具类型之 Pick 类型1. 什么是对象类型转换?2. 什么是 TypeScript Pick?2.1 用 Pick<Type,

typescript 实用工具类型之 omit 类型_夏安   的博客-爱代码爱编程

TypeScript 实用工具类型之 Omit 类型 TypeScript 实用工具类型之 Omit 类型1. 示例2. 应用于 Interface3. 谨慎使用4. 小结 TypeScript 实用工具类

typescript 实用工具类型之 partial 类型_夏安   的博客-爱代码爱编程

TypeScript 实用工具类型之 Partial 类型 TypeScript 实用工具类型之 Partial 类型1. 场景概述2. Partial<Type>3. 使用 Interface4. 小结

typescript常用的泛型工具类型-爱代码爱编程

泛型工具类型 1 Partial type所有属性变成可选 interface Props{ id:number, name:string } type PartialProps = Partial<

typescript实用工具类型-爱代码爱编程

分享几种实用的工具类型,分别是:Partial、Required、Pick、Omit、Exclude、Readonly、Record Partial 生成一个新的类型,所有属性与原类型的属性相同,但都为可选项 inte

typescript实用工具类-爱代码爱编程

目录 一、与对象相关的工具类 1、Partial 2、Required 3、Readonly 4、 Record,type> 5、 Pick,keys> 6、Omit,keys> 二、与类型有关的工具类  1、Exclude ,excludedunion> 2、Extract,> 3、NonNulla

typescript 实用工具类型_typescript 工具库-爱代码爱编程

TypeScript 实用工具类型 Partial Readonly Record Pick Omit Exclude Partial 作用: 生成一个新类型 该类型和 T 拥有相同的属性 但是所有属性皆为可选项 (构

typescript中的工具类型_typescript recordable-爱代码爱编程

keyof keyof可以用于获取某种类型的所有键,其返回值类型为联合类型(string | number | …),其可以作用域普通对象,索引签名,枚举类型等等。 例子: // 例1: // 此时K 会遍历 T对象中的key值,并且限制输入obj中不存在的键 function getKey<T extends object, K extend

typescript:内置工具类型_typescript 工具类型-爱代码爱编程

Typescript提供了一些比较使用的工具类型,这些类型都返回一种新的类型,这种新的类型都是对提供的类型进行一些操作而生成。根据工具类型返回的类型的不同,我们把它们分为对象类型、非对象类型。 对象类型 这一主题下的工具

typescript 常用工具(partial、readonly、record、pick、omit、required、instancetype)_typescript pick record-爱代码爱编程

工具类型 Partial 构造类型 Type,并将它所有的属性设置为可选的。它的返回类型表示输入类型的所有子类型。 type Person = { name: string, age: number, se

typescript 中常用的内置工具类型_typescript 工具类型-爱代码爱编程

TypeScript 中常用的内置工具类型: 一:操作接口类型 1. Partial:可以将类型的所有属性都变为可选的 1.源码 type Partial<T> = { [P in keyof T

typescript常用工具类型(utility types)_typescript 工具类-爱代码爱编程

目录 前言 一、Partial 二、Required 三、Readonly 总结 前言 TypeScript提供了很多工具类型,供使用者方便的从一个类型转换到另一个类型。下面介绍几种常用的工具类型和使用场景,以便更好的应用TypeScript校验,减少我们代码出错的机率。 一、Partial<Type>