This is the 10th day of my participation in Gwen Challenge
2021-06-10 TypeScript Utility Types
Relearn TypeScript and dig into common TSUtility Types
1. UnderstandUtility Types
The warm-up
1.1 keyof
The purpose of keyof is that, assuming T is a type, the type produced by keyof T is a combination of the attribute name string literal types of T. How do you visualize it? Look at the following code:
interface exampleA {
name:string;
id:number;
create:string;
}
type TypeA = keyof exampleA; / / it is equivalent to 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)
Copy the code
1.2 in
The operator
So what in does is it iterates over union types for example
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 )
Copy the code
1.3 in keyof T
和 extends keyof T
One is the exact match query and the other is the contain query
Two commonly usedUtility Types
2.1 Partial<T>
Construct a type for which the types of all properties are set to optional. This utility returns a type that represents all subsets of a given type. Such as:
interface A {
name:string;
id:string
}
let a: Partial<A> = {
name:'tangjie'
}
console.log(a)
Copy the code
Partial implementations:
type Partial<T> = {
[K inkeyof T]? : T[K]; }Copy the code
The opposite is Required
2.2 Pick<Type, Keys>
Type is constructed by selecting an attribute key set (a string, literal, or a combination of string text) from Type.
interface A {
id: string;
name: string;
age: number;
}
type B = Pick<A, "name" | "age">;
const xiaoming: B = {
name: "xiaoming".age: 26};Copy the code
Pick is implemented as follows:
type Pick<T,K extends keyof T> = {
[P in K]: T;
}
Copy the code
2.3 Omit<Type, Keys>
Type is constructed by selecting all the attributes in Type and then removing the key (string, literal, or union of string text).
interface A {
id: string;
name: string;
age: number;
}
const a:Omit<A,'id'> = {
name:'tangjie'.age:18.// id:1 error if this attribute is added
}
Copy the code
2.4 Parameters<Type>
Constructs a tuple type from the type used in the argument of a function type type.
declare function f1(arg: { a: number; b: string }) :void;
type A = Parameters<() = > string>;// equivalent to A = []
type B = Parameters<(s: string) = > void>;// equivalent to B = [s: string]
Copy the code
3. Summary
The most difficult part of TS is the use of generics. Through the above implementation idea of TS native support Utility Type, we can help us to understand a lot of details about the use of generics. More Utility types can go to GitHub, which is a third party