当前位置:网站首页>TS advanced infer
TS advanced infer
2022-06-23 04:40:00 【JonnyLan】
In the previous article, we introduced condition types , In this article, let's introduce a very practical infer How to use .
Introduction
The basic syntax of conditional types introduced in our last article is :
T extends U ? X : Y;
If the placeholder type U Is a type that can be broken down into several parts , For example, array type , A tuple type , Function type , String literal type, etc . At this time, you can go through infer To get U The type of a part of a type .
infer The grammatical restrictions are as follows :
inferOnly in conditional type of extends Used in clausesinferThe type obtained can only be intrueUse in statement , namelyXUse in
Infer array ( Or tuple ) The type of
Usage method
type InferArray<T> = T extends (infer U)[] ? U : never;
(infer U)Peace often writesstring[],number[]Wait, is it like ? And here is through(infer U)To get the type corresponding to the array .
Case study
type I0 = InferArray<[number, string]>; // string | number
type I1 = InferArray<string[]>; // string
type I2 = InferArray<number[]>; // number
Infer array ( Or tuple ) The type of the first element
Usage method
type InferFirst<T extends unknown[]> = T extends [infer P, ...infer _] ? P : never
[infer P, ... infer _]ininfer P AcquiredIs the type of the first element , and...infer _Get the array type of other remaining elements of the array ;
In particular , Our example summary does not need to use the types of other elements , So use_.
Case study
type I3 = InferFirst<[3, 2, 1]>; // 3
Infer array ( Or tuple ) The type of the last element
Usage method
type InferLast<T extends unknown[]> = T extends [... infer _, infer Last] ? Last : never;
This and Infer the type of the first element of the array similar ,
...infer _Get all the element types before the last element ,infer LastGet the type of the last element .
Case study
type I4 = InferLast<[3, 2, 1]>; // 1
Infer parameters of function types
Usage method
type InferParameters<T extends Function> = T extends (...args: infer R) => any ? R : never;
...argsRepresents a tuple of function parameters ,infer RRepresents the type of tuple formed by the inferred function parameters .
Case study
type I5 = InferParameters<((arg1: string, arg2: number) => void)>; // [string, number]
Infer the return value of a function type
Usage method
type InferReturnType<T extends Function> = T extends (...args: any) => infer R ? R : never;
And the one in front
Infer parameters of function typessimilar ,=>hinderinfer RRepresents the return value type of the inferred function .
Case study
type I6 = InferReturnType<() => string>; // string
infer Promise Type of success value
Usage method
type InferPromise<T> = T extends Promise<infer U> ? U : never;
Case study
type I7 = InferPromise<Promise<string>>; // string
Infer the literal type corresponding to the first character of the string literal type
Usage method
type InferString<T extends string> = T extends `${infer First}${infer _}` ? First : [];
Case study
type I8 = InferString<"Johnny">; // J
Comprehensive case
Let me give you some comprehensive examples , I will not introduce the functions implemented by these examples , Let's feel it infer Use skills , See if you can see the functions at a glance :
type Shift<T> = T extends [infer L, ...infer R]? [...R] : [];
type Pop<T extends any[]> = T extends [...infer L, infer R] ? [...L] : [];
type Reverse<T extends unknown[], U extends unknown[] = []> = [] extends T
? U
: T extends [infer L, ...infer R]
? Reverse<R, [L, ...U]>
: U;
type FlipArguments<T extends Function> = T extends (...arg: infer R) => infer S ? (...arg : Reverse<[...R]>) => S : T;
type StartsWith<T extends string, U extends string> = T extends `${U}${infer R}` ? true : false;
type TrimLeft<S extends string> = S extends `${infer L}${infer R}`
? L extends ' ' | '\n' | '\t'
? TrimLeft<R>
: S
: '';
type Trim<S extends string> = S extends `${' ' | '\t' | '\n'}${infer R}`
? Trim<R>
: S extends `${infer L}${' ' | '\t' | '\n'}`
? Trim<L>
: S;
type StringToUnion<T extends string, U = never> = T extends ''
? U
: T extends `${infer L}${infer R}`
? StringToUnion<R, U | L>
: U;
These examples involve two knowledge points that are not introduced : Template literal type and Recursive type , If you don't understand these two knowledge points, you can refer to other articles . I will also introduce these two knowledge points later .
边栏推荐
- Principle of 8-bit full adder
- Pta:7-61 teacher student information management
- PTA:6-71 时钟模拟
- There is a problem with redis startup
- Create a desktop shortcut to your appimage
- Xiaojinwei, chairman of Chenglian Technology: implement the national strategy of data economy and lead the development of new consumption in the digital era!
- 在线文本过滤小于指定长度工具
- Photoshop PS viewing pixel coordinates, pixel colors, pixel HSB colors
- PTA:7-37 学号解析
- Please use the NLTK Downloader to obtain the resource
猜你喜欢

Svg+js smart home monitoring grid layout

Software development in 2022: five realities CIOs should know

What are the characteristics of SRM supplier management system developed by manufacturing enterprises

【多模态】UNIMO

Principle of 8-bit full adder

Photoshop PS viewing pixel coordinates, pixel colors, pixel HSB colors

什么是元数据
![[advanced binary tree] AVLTree - balanced binary search tree](/img/a5/aef68dd489ef5545e5b11ee2d3facc.png)
[advanced binary tree] AVLTree - balanced binary search tree
![[multimode] unimo](/img/a5/a857e20e1432ef3623527c8655a49a.png)
[multimode] unimo

svg d3. JS generate tree tree view
随机推荐
Deploying Apache pulsar on kubesphere
自动化测试常见的面试题
Permission Operation in dynamics 365 plug-in
Pta:7-60 pet growth
Pta:6-29 application of virtual base classes - people, teachers and students
给你的AppImage创建桌面快捷方式
What are the characteristics of SRM supplier management system developed by manufacturing enterprises
Lighthouse locally deployed TCA code analysis tool
#17生成器的函数声明与调用
Leetcode 1208. 尽可能使字符串相等
Can MySQL be used in Linux
Pta:7-61 teacher student information management
Bug STM32 interrupt (everyone knows)
3D数学基础[十六] 匀加速直线运动的公式
OpenJudge NOI 1.13 50:数根
1183. 电力
Monitoring artifact ZABBIX, from deployment to application, goes deep layer by layer
P1363 幻象迷宫(dfs)
How MySQL deletes a row of data in a table
抖音x-bogus和_signature参数分析