重学TypeScript,深入常见的TS的`Utility Types`

这是我参与更文挑战的第 10 天,活动详情查看: 更文挑战

2021-06-10 TypeScript Utility Types

重学TypeScript,深入常见的TS的Utility Types

1. 了解Utility Types 的热身

1.1 keyof

keyof的作用是,假设T是一个类型,那么keyof T产生的类型是T的属性名称字符串字面量类型构成的联合类型。怎么直观理解呢?看下面代码:

interface exampleA {
  name:string;
  id:number;
  create:string;
}

type TypeA = keyof exampleA; // 其实就相当于 type TypeA = 'name'|'id'|'create'
let b:TypeA = 'name';
b = 'id';
// b = 'end'; // Type '"end"' is not assignable to type 'keyof exampleA'
console.log(b)
复制代码

1.2 in操作符

in的作用就是遍历联合类型例如

type A = 'a'|'b'|'c';
type Obj = {
	[p in A]: string
} // {a: any, b: any}

const a:Obj = {
  a:'test',
  b:'test',
  // Property 'c' is missing in type '{ a: string; b: string; }' but required in type 'Obj
  // c:'test'
}
console.log( a )
复制代码

1.3 in keyof Textends keyof T

一个是精确匹配查询,一个是包含查询

2 常用的Utility Types

2.1 Partial<T>

构造一个类型,其所有属性的类型都设置为可选。此实用程序将返回表示给定类型的所有子集的类型。例如:

interface A {
  name:string;
  id:string
}

let a: Partial<A> = {
  name:'tangjie'
}
console.log(a)
复制代码

Partial的实现方式:

type Partial<T> = {
	[K in keyof T]?: T[K];
}
复制代码

功能与之相反的是Required<T>

2.2 Pick<Type, Keys>

通过从Type中选择属性键集(字符串、文字或字符串文本的联合)来构造类型。

interface A {
  id: string;
  name: string;
  age: number;
}
type B = Pick<A, "name" | "age">;

const xiaoming: B = {
  name: "xiaoming",
  age: 26,
};
复制代码

Pick的实现方式:

type Pick<T,K extends keyof T> = {
	[P in K]: T;
}
复制代码

2.3 Omit<Type, Keys>

通过选择Type中的所有属性,然后移除键(字符串、文字或字符串文本的联合)来构造类型。

interface A {
  id: string;
  name: string;
  age: number;
}

const a:Omit<A,'id'> = {
	name:'tangjie',
	age:18,
	// id:1 如果加了这个属性就报错
}

复制代码

2.4 Parameters<Type>

从函数类型类型的参数中使用的类型构造元组类型。

declare function f1(arg: { a: number; b: string }): void;
type A = Parameters<() => string>;// 相当于A = []    
type B = Parameters<(s: string) => void>;// 相当于 B = [s: string]
复制代码

3.总结

ts最难的地方估计也就是对泛型的使用,通过上面的Ts原生支持的Utility Type的实现思路,能够帮我们掌握很多关于泛型使用的细节,更多utility type可以去这个GitHub,这个就是第三方的啦~

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享