Skip to main content

Ts 工具类型

  • ConstructorParameters 类构造函数的参数类型的元祖

  • Exclude 排除两个类型的交集

    type Animal = Dog | Cat;  
    type NonDog = Exclude<Animal, Dog>; // 排除 Dog 类型,剩下 Cat 类型
  • Extract 选择给可分配另一种类型的字类型;用于从联合类型中提取出某个子类型。

    type Animal = Dog | Cat | A ;  
    type DogOnly = Extract<Animal, Dog | A>; // 提取出 Dog | A 类型
  • InstanceType 获取构造函数的实例类型

  • NonNullable 从类型中排出 null 和 undefined

  • Parameters 函数参数类型的元祖(注意使用typeof)

    function handleAnimal(animal: Dog | Cat) {  
    // 处理逻辑
    }

    type AnimalParams = Parameters<typeof handleAnimal>; // 获取 handleAnimal 函数的参数类型
  • Partial 把对象中的所有属性设为可选

  • Readonly 使对象中的所有属性为只读,数组 or 元祖

  • RealonlyArray 制作给定类型的不可变数组

  • Pick 从一个复合类型中取出几个想要的类型组合

  • Record 键类型到值类型的映射

  • Required 使对象中的所有属性为必需

  • Omit 排除一些字段

  • ReturnType 获取函数类型的返回类型, 注意配合typeof使用

    function isDog(animal: Dog | Cat): animal is Dog {  
    return (animal as Dog).bark !== undefined;
    }

    type DogType = ReturnType<typeof isDog>; // 获取 isDog 函数的返回类型

常用工具函数


type a = Array<{a:string}&({b:boolean}|{c:number})>
{a:string;b:boolean}{a:string;c:number}

// 工具类型都是用类型别名实现的
ts写在泛型<>中的typeof和js中不同,是在编译时就执行,js的typeof只有运行时才执行
[Aa,Ab]: Parameters<type A>

// interface不能使用
type Person = {
name: string,
age: number
}
// Partial会对type中每一个做?处理
const xiaoMing: Partial<Person> ={age:13}
// 也可以形成一个新type
type a = Partial<A>

// 会对type中去掉一个类型
const xiaoAi: Omit<Person,'name'>={age:13}
const xiaoAi: Omit<Person,'name'|'age'>={}
type A = Exclude<a,'name'>

// 但是exclude是从联合类型&中去掉一个,omit是从键值对中去掉一个

完全复制
type a<T> = {
[P in keyof T]: T[P]
}
// Partial的实现,重点在于?
type Partial<T> = {
[P in keyof T]?: T[P]
}

// K必须要在T的键集合当中
type Pick<T, K extends keyof T> = {
[P in K]: T[P]
}
// 如果T在U中则返回never,否则返回T 由于是联合类型,不能用keyof
type Exclude<T,U> = T extends U? never: T

// K extends keyof any保证可以填联合类型,挨个pick出不是K的
type Omit<T,K extends keyof any> = Pick<T, Exclude<keyof T,K>>