当前位置:网站首页>TS advanced keyof
TS advanced keyof
2022-06-13 11:32:00 【JonnyLan】
Finished painting type-challenges After all the simple and medium difficulty questions , Yes TypeScript There are some new understandings and understandings about the type operation of . Here are a few articles to record some important knowledge points .
This series of articles requires your understanding of TypeScript Have a basic understanding of
Basic usage
JavaScript adopt Object.keys() Get all attribute key values of the object , and typescript The main focus is on type operations , adopt keyof Operator can get all the key types in the object Joint type .
In order to know more about keyof The action of the operator , Let's use some examples to explain :
type Person = {
id: number;
name: string;
age: number;
};
type P1 = keyof Person; //'id' | 'name' | 'age'
keyofOperator getsPersonAll key value types of type, i.e'id','name'and'age'Three Literal type The type of association formed'id' | 'name' | 'age'.
The practical application
Next, I will use some examples to explain keyof Application .
Get the types of all properties of the object
type P2 = Person[keyof Person]; // number | string
Person['key']yes Query type (Lookup Types), You can get the type of the corresponding attribute type ;Person[keyof Person]It's essentially executionPerson['id' | 'name' | 'age'];- Because of the distributed nature of union types ,
Person['id' | 'name' | 'age']Turned intoPerson['id'] | Person['name'] | Person['age'];- The final result is
number | string.
Constraining the range of the norm parameter
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type P3 = MyPick<Person, 'id' | 'age'>
K extends keyof TYesKThere is a constraint , Can only be'id','name','age'A union type consisting of one or more types in ;- Without this constraint ,
{ [P in K]: T[P] }May be an error .
And mapping types to achieve certain functions
- Add... To all attributes of the object type
readonlyModifier
type MyReadonly<T> = { readonly [P in keyof T]: T[P] };
type P4 = MyReadonly<Person>; // { readonly id: number; readonly name: string; readonly age: number; }
[P in keyof T]Is to traverse the key value types of all attributes , From the casePNamely'id','name'and'age';T[P]Is the query type , It was introduced above ,Person['id']The result isnumber,Person['name']The result isstring,Person['age']The result isnumber.- Add each attribute type
readonlyModifier , The end result is{ readonly id: number; readonly name: string; readonly age: number; }
- Remove some attributes of the object type
Microsoft officials are through Pick and exclude Combine to achieve Omit Logical , We can achieve the same function through the following code .
type MyOmit<T, K> = { [P in keyof T as P extends K ? never : P]: T[P] };
type P5 = MyOmit<Person, 'id' | 'name'> // {age: number;}
In code
as P extends K ? never : PThis part of the code is called Remap , Because what we don't necessarily need isP, In some cases, it is necessary toPMake some conversions ; In the caseKIt containsPThe key value type is throughneverIgnored , On the contrary, keep . So the end result is{age: number;}
- Add new attributes to the object type
type AppendToObject<T, U extends keyof any, V> = {[P in keyof T | U]: P extends keyof T ? T[P] : V}
type P6 = AppendToObject<Person, 'address', string> // { address: string; id: number; name: string; age: number; }
And condition types to realize functions
- The two object types are merged into a new type
type Merge<F extends Record<string, any>, S extends Record<string, any>> = {
[P in keyof F | keyof S]: P extends keyof S ? S[P] : P extends keyof F ? F[P] : never;
};
type Skill = {
run: () => void;
}
type P7 = Merge<Person, Skill>; // { id: number; name: string; age: number; run: () => void; }
In the case
P extends keyof S ? X : YThe part of is calledCondition type( It will also be introduced separately later ). The meaning in the code is ifPyesFProperty type of , Then takeF[P], IfPyesSProperty type of , Then takeS[P].
Summary
After the introduction , Should be right keyof There is some feeling in the use of . Let me list some code , You can feel it :
type _DeepPartial<T> = { [K in keyof T]?: _DeepPartial<T[K]> }
type Diff<T extends Record<string, any>, U extends Record<string, any>> = {
[P in keyof U | keyof T as P extends keyof U
? P extends keyof T
? never
: P
: P extends keyof T
? P
: never]: P extends keyof U ? U[P] : P extends keyof T ? T[P] : never;
};
This implementation logic involves other knowledge points, which is a little complicated , It doesn't matter if you don't fully understand it , Later on .
边栏推荐
- 乘法逆元作用
- fastapi 如何响应文件下载
- QT 窗体的show/exec、close/hide,调用close析构没有执行
- [tcapulusdb knowledge base] tcapulusdb tmonitor module architecture introduction
- 高斯消元求n元方程组
- Vivo large scale kubernetes cluster automation operation and maintenance practice
- F2. nearest beautiful number (hard version)
- Actual combat analysis of malicious code lab05-01
- Apache APISIX v2.14.1 探索性版本发布,进军更多领域
- Log 1111
猜你喜欢

17 pictures: read and understand the first domestic guide for mainframe security capacity building

数据库连接数设置多少合适?

【TcaplusDB知识库】Tmonitor后台一键安装介绍(二)

很妙的贪心(F2. Nearest Beautiful Number (hard version))

Nim游戏阶梯 Nim游戏和SG函数应用(集合游戏)

【TcaplusDB知识库】TcaplusDB机型管理介绍

ue5 小知识点 geometry script modeling

Navicat connection MySQL in Pagoda

ue5 小知识点 random point in Bounding Boxf From Stream

状态压缩DP例题(旅行商问题和填矩形问题)
随机推荐
【TcaplusDB知识库】TcaplusDB新增机型介绍
求组合数四种方法
Environ. Sci. Technol. (if=9.028) | impact of urban greening on atmospheric environment
(幼升小信息-03)批量模板制作 幼儿基本信息收集文件夹(包含PDF、Word、证件文件夹)
22、ADS使用记录之E类功放设计(下)
ARM64 上的性能怪兽:API 网关 Apache APISIX 在 AWS Graviton3 上的安装和性能测试
5.5 clock screensaver
【TcaplusDB知识库】TcaplusDB Tmonitor模块架构介绍
乘法逆元作用
很妙的贪心(F2. Nearest Beautiful Number (hard version))
【TcaplusDB知识库】TcaplusDB单据受理-创建游戏区介绍
QT 窗体的show/exec、close/hide,调用close析构没有执行
Pagoda add a website: PHP project
[tcapulusdb knowledge base] Introduction to tmonitor stand-alone installation guidelines (I)
【Verilog向SystemVerilog过渡遇到的问题】~ 信号变量类型的转变、 == 和 ===的区别
2021CCPC网络赛题解加总结
Four methods of finding combinatorial numbers
塔米狗知识|全面剖析国有企业并购含义及其作用
COM的模式变化引起的IPdu Handling【接收截止日期监控】
[tcapulusdb knowledge base] tcapulusdb doc acceptance - Introduction to creating game area