当前位置:网站首页>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 .
边栏推荐
- ue5 小知识点 geometry script modeling
- 很妙的贪心(F2. Nearest Beautiful Number (hard version))
- 2021CCPC网络赛题解加总结
- Multiplicative inverse action
- 基于Vue+Nest.js+MySQL的跨平台开源社区运营管理系统
- ACP | 东北地理所在气象-空气质量双向耦合模式研究中取得进展
- Multithreading starts from the lockless queue of UE4 (thread safe)
- Easyclick run code snippet out null
- 面试技巧问答
- Ipdu handling caused by mode change of COM
猜你喜欢

Do you agree that the salary of hardware engineers is falsely high?

Euler function and finding Euler function by linear sieve

View the default MySQL password in the pagoda

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

Nim game ladder Nim game and SG function application (set game)
![[tcapulusdb knowledge base] Introduction to tmonitor background one click installation (II)](/img/89/1b3a301c72eef78658744383ef5124.png)
[tcapulusdb knowledge base] Introduction to tmonitor background one click installation (II)

2021CCPC网络赛榜单

vivo大规模 Kubernetes 集群自动化运维实践

Performance monster on arm64: installation and performance test of API gateway Apache APIs IX on AWS graviton3
![[tcapulusdb knowledge base] Introduction to tmonitor stand-alone installation guidelines (I)](/img/f5/7ad04670229b99ea727f942d82328b.png)
[tcapulusdb knowledge base] Introduction to tmonitor stand-alone installation guidelines (I)
随机推荐
socket编程(中)
COM的模式变化引起的IPdu Handling【接收截止日期监控】
(幼升小信息-03)批量模板制作 幼儿基本信息收集文件夹(包含PDF、Word、证件文件夹)
SSM integration preliminary details
The road of ospo construction of Weibo: how to promote enterprise open source through ospo construction?
C#/VB. Net to generate directory bookmarks when word is converted to PDF
Euler function and finding Euler function by linear sieve
音视频技术开发周刊 | 249
We spent a weekend migrating 3.7 million lines of code to typescript
《气候韧性和可持续性》| 新研究表明超级飓风未来几年会对南亚产生更大破坏
Tamidog knowledge | a comprehensive analysis of the meaning and role of mergers and acquisitions of state-owned enterprises
Environ. Sci. Technol. (if=9.028) | impact of urban greening on atmospheric environment
领导说要明天上线,这货压根不知道开发流程
MFC custom button to realize color control
ue5 小知识点 geometry script modeling
基于Vue+Nest.js+MySQL的跨平台开源社区运营管理系统
区间修改乘和加(理解懒标记的好例题)
【TcaplusDB知识库】TcaplusDB机型管理介绍
F2. nearest beautiful number (hard version)
C#/VB.NET 在Word转PDF时生成目录书签