ts常用语法笔记(Omit,Pick,Partial,Required)

发布时间 2023-05-23 16:25:06作者: 芝麻小仙女

1.Omit【某个类型中去除某些项后的新的数据类型】

-需要两个参数:Omit<type, string>,第一个参数为要继承的type类型,第二个参数为想要去除的key的字符串,存在多个时用|分隔

源码:
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>

  

e.g.

export type AsyncButtonConfirmProps = Omit<PopconfirmProps, 'children' | 'onConfirm'>;
即为PopconfirmProps中去除children、onConfirm这两个项后剩余的项,构造成AsyncButtonConfirmProps 这个新的数据类型
 
-----------------------------------------------------------------------------------
 
2.Pick【某个类型中选取一组指定属性,构造成新的数据类型】
-两个参数:Pick<type, string>,第一个参数为被选取的类型,第二个参数为选取的属性,存在多个时用|分隔
源码:
type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
}
 
e.g.
export type AsyncButtonConfirmProps = Pick<PopconfirmProps, 'children' | 'onConfirm'>;
即为PopconfirmProps中选取children、onConfirm这两个项,构造成AsyncButtonConfirmProps 这个新的数据类型。此时AsyncButtonConfirmProps 的属性为{children: children的类型;onConfirm:onConfirm的类型;}
-----------------------------------------------------------------------------------
 
3.Partial【将类型中所有的项都调整为可选属性(即加上?)
-Partial<type>,一个参数,为要调整的类型
源码:
type Partial<T> = {
    [P in keyof T]?: T[P];
}
 
e.g.
export interface Type = {
name: string;
}
export interface PartialType = Partial<Type>;
即PartialType 的属性为Type的属性全部变为了可选,如下:
PartialType  = {
name?: string;
}
-----------------------------------------------------------------------------------
 
4.Required【将类型中所有的项都调整为必选属性(即去掉?)】
-Required<type>,一个参数,为要调整的类型
 
源码:
type Required<T> = {
    [P in keyof T]-?: T[P];
}

  

e.g.
export interface Type = {
name?: string;
}
export interface RequiredType = Partial<Type>;
即RequiredType 的属性为Type的属性全部变为了必选,如下:
RequiredType = {
name: string;
}
----------------------------------------------------------------------------------
 
5.数据类型加指定的类型
-export type AddId<T, P = string> = T & {id: P};
 
e.g.
export interface TypeAddId = AddId<Type>
即给Type加上了AddId的项,构成新的数据类型