当前位置:网站首页>TS advanced condition type
TS advanced condition type
2022-06-13 11:32:00 【JonnyLan】
Front end developers are right about Javascript You should be familiar with ternary expressions in , It is very convenient to get different output results according to the input values by using ternary expressions . TypeScript A similar syntax is provided for types , and Javascript The only difference is TypeScript The operation is data type .
Basic grammar
Basic use
T extends U ? X : Y;
TUXYFour are placeholders , They represent four types ;T extends UExpressTTypes can be assigned toUtype , It also involves TS Type compatibility .
A few simple examples
- Determine whether the type is
stringtype
type IsString<T> = T extends string ? true : false;
type C11 = IsString<string>; // true
type C22 = IsString<number>; // false
type C1 = IsString<"1">; // true
type C2 = IsString<1>; // false
a key : In the example
trueandfalseIt's the type ( Literal type ), It's not worth it .
- If it is
AnimalType getnumbertype , Otherwisestringtype
interface Animal {
live(): void;
}
interface Dog extends Animal {
woof(): void;
}
type IsAnimal<T> = T extends Animal ? number : string;
type C3 = IsAnimal<Dog> // number
type C4 = IsAnimal<RegExp> // string
TS Advanced keyof Examples in
- Realization
Omit
type MyOmit<T, K> = { [P in keyof T as P extends K ? never : P]: T[P] };
- Add attributes to object types
type AppendToObject<T, U extends keyof any, V> = {[P in keyof T | U]: P extends keyof T ? T[P] : V}
Condition types can be used in combination
Examples are as follows : Gets the name of the type
type TypeName<T> = T extends string
? 'string'
: T extends number
? 'number'
: T extends boolean
? 'boolean'
: T extends undefined
? 'undefined'
: T extends Function
? 'function'
: 'object';
This method of use should also be easy to understand , But more explanation .
Distribution properties of condition types
If the Distribution properties of condition types Students who are not familiar with you may be right Exclude,Extract And other tool types , Next I'll use Exclude Let's introduce it in detail Distribution properties of condition types .
a key : The conditional distribution feature is mainly aimed at
TIt's a joint type
Exclude The concrete execution logic of
type Exclude<T, U> = T extends U ? never : T;
type C5 = Exclude<'a' | 'b' | 'c', 'a' | 'b'> // 'c'
explain :
- For union types
TDistribution becomes :'a' extends 'a'| 'b' ? never : 'a' | 'b' extends 'a'| 'b' ? never : 'b' | 'c' extends 'a'| 'b' ? never : 'c'
- The result of the separate calculation is
never | never | 'c'- The final result :
c
Distribution of condition type must be a raw type
A bare type is one that has not been Array , Tuples and Promise And so on .
Comparative examples are as follows :
type IsString2<T> = [T] extends string[] ? "IS a String" : "Not a String";
type C7 = IsString2<string | number>;
// result : "Not a String"
type IsString3<T> = T extends string ? "IS a String" : "Not a String";
type C8 = IsString3<string | number>;
// result : "IS a String" | "Not a String"
IsString2Medium[T]Wrapped in an array , No distribution , Direct judgment[string | number] extends string[], Got it"Not a String";IsString3Medium[T]Not packed , Will be distributed , obtain"IS a String" | "Not a String";
never Is an empty union type
If you decide whether a type is never, Perhaps the first thing I thought of was :
type IsNever<T> = T extends never ? true : false; //
This is wrong , because never Represents an empty union type , It's equivalent to not having , All will not execute , Finally never type , Will not get true.
The correct solution logic is to never Just change to tuple type .
type IsNever<T> = [T] extends [never] ? true : false; //
Some cases
Get the type of the first element of the array type
type First<T extends any[]> = T extends never[] ? never : T[0];
type arr1 = ['a', 'b', 'c']
type C6 = First<arr1> // 'a'
Be careful there
'a','b','c', It's the type , It's the type , It's the type ;
Pick Properties with a certain type
type PickByType<T, U> = { [P in keyof T as T[P] extends U ? P : never]: T[P] };
type OnlyBoolean = PickByType<{
name: string
count: number
isReadonly: boolean
isEnable: boolean
}, boolean>
// result :
{
isReadonly: boolean;
isEnable: boolean;
}
Judge Any
export type IsAny<T> = 0 extends (1 & T) ? true : false
type IsAny<T> = 0 extends (1 & T) ? true : false
type C9 = IsAny<any>; // true
type C10 = IsAny<string>; // false
explain :
any & 1 = any,0 extends anyestablish , So backtrue; Explain the address in detail
Judge that the two types are exactly equal
export type Equal<X, Y> =
(<T>() => T extends X ? 1 : 2) extends
(<T>() => T extends Y ? 1 : 2) ? true : false
explain : By constructing a function type, we can compare whether the two function types are exactly equal . Explain the address in detail
infer
Conditional type syntax can use infer Type inference , The next part mainly introduces this part .
Let's start with an official example of getting parameter types :
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
边栏推荐
- Web3 system construction: principles, models and methods of decentralization (Part I)
- 【TcaplusDB知识库】TcaplusDB单据受理-创建游戏区介绍
- Pagoda add a website: PHP project
- [tcapulusdb knowledge base] Introduction to new models of tcapulusdb
- (幼升小信息-04)如何用手机WPS在PDF上进行电子签名
- 【TcaplusDB知识库】Tmonitor后台一键安装介绍(一)
- Digital DP example
- 【TcaplusDB知识库】TcaplusDB集群管理介绍
- fastapi 如何响应文件下载
- Multithreading starts from the lockless queue of UE4 (thread safe)
猜你喜欢

Based on vue+nest Js+mysql cross platform open source community operation management system

Digital DP example

【TcaplusDB知识库】TcaplusDB Tmonitor模块架构介绍

MIIdock文件分布

Anonymity in Web3 and NFT

Tamidog knowledge | a comprehensive analysis of the meaning and role of mergers and acquisitions of state-owned enterprises
![[tcapulusdb knowledge base] Introduction to new models of tcapulusdb](/img/ae/ef8536931569d736caec773148556e.png)
[tcapulusdb knowledge base] Introduction to new models of tcapulusdb

socket编程(中)
![[tcapulusdb knowledge base] tcapulusdb Model Management Introduction](/img/2a/2a3d1b813ea6ed58695e9deac05b0d.png)
[tcapulusdb knowledge base] tcapulusdb Model Management Introduction

音视频技术开发周刊 | 249
随机推荐
The leader said he would go online tomorrow, but he didn't know the development process at all
恶意代码实战分析Lab05-01
5.5 clock screensaver
Pagoda add a website: PHP project
[tcapulusdb knowledge base] tcapulusdb doc acceptance - create business introduction
[dynamic planning] beginner level
It's the first time that the programmer interview pays so much attention to the concept of investigation
QT 窗体的show/exec、close/hide,调用close析构没有执行
Will it be a great opportunity for entrepreneurs for Tiktok to attach so much importance to live broadcast sales of takeout packages?
MIIdock文件分布
硬件工程师薪资虚高,你认可吗?
Miidock file distribution
Interval modification multiplication and addition (a good example of understanding lazy tags)
Nim游戏阶梯 Nim游戏和SG函数应用(集合游戏)
【TcaplusDB知识库】TcaplusDB Tmonitor模块架构介绍
Apache apisik v2.14.1 exploratory release to expand into more fields
Pagoda access changed from IP to domain name
我是如何解决码云图床失效问题?
【TcaplusDB知识库】TcaplusDB运维单据介绍
日志1111