笔记-Typescript内置工具类型

38 阅读2分钟
  1. Partial 将类型T的属性都变为可选属性,并构造一个新类型
1 interface Inter {
2     name: string
3     age:number
4 }
5 
6 type T = Partial<Inter> // { name?: string; age?: number; }
  1.  Required  将类型T的属性都变为必选属性,并构造一个新类型  和 Partial正好相反
interface Inter { 
    name?: string
    age?:number
}

type T = Required<Inter> // { name: string; age: number; }
  1. Readonly 构造一个新类型,并将实际类型参数T中的所有属性变为只读属性
interface A {
    x: number
    y: number
}
type T = Readonly<A>; // // { readonly x: number; readonly y: number; }
const a: T = { x: 0, y: 0 };
// a.x = 1;   // 编译错误!不允许修改
// a.y = 1;   // 编译错误!不允许修改
  1. Record<K,T>  构建一个属性名类型为K的联合类型,值为T类型的对象类型
type K = 'x' | 'y';
type T = number;
type R = Record<K, T>; // { x: number; y: number; }
const a: R = { x: 0, y: 0 };  //  x' y 不能缺失任何一个
    
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" },
}

Record 实现源码:

/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};
    
K中的所有属性值都转换为T类型,并将返回的新类型返回给proxyKType,K可以是联合类型、对象、枚举…  

type K = 'name' | 'age' | 'sex'
type T = string
type Ks = K | 'height' // 追加属性
type R = Record<Ks, T>

const LILI: R  = {
    name: 'LILI', 
    sex: 'man',
    age: '12', 
    height:'178'
}
  1. Pick<T,K>  从已有类型T中选组指定类型 K 中的属性及其类型后构建出一个新德对象类型
interface A { 
    x: number
    y: string
}
type T = Pick<A,'x'> // { x: number; }
interface SuperbUser {
  userId: number;
  macAddress: string;
  username: string;
  email: string;
  password: string;
  firstName: string;
  lastName: string;
  roles: ('Admin' | 'Editor' | 'Author')[]
};

type GuestUser = 'userId' | 'macAddress' | 'username'
type T = Pick<SuperbUser , GuestUser> // { userId: number; macAddress: string; username: string; }
    
const USER: T = {  
    userId: 1001,  
    macAddress: '58962535',  
    username:'XIANA'  
}

// console.log(USER.roles) // 错误 Property 'roles' does not exist on type 'Pick<SuperbUser, GuestUser>'.

  1.  Omit<T,K> 与 Pick相反 剔除类型T中存在的K类型后构建出一个新类型     该属性 在 TS 3.5.1 中添加,旧版本的 TS不支持  使用“skipLibCheck”:true作为tsconfig.json文件中的编译器选项。
interface A { 
    x: number
    y: string
}
type T = Omit<A,'x'> // { y: number; }