当前位置:网站首页>Key value judgment in the cycle of TS type gymnastics, as keyword use
Key value judgment in the cycle of TS type gymnastics, as keyword use
2022-07-06 07:29:00 【Jioho_】
TS Type gymnastics And Key value judgment in the loop ,as Keyword use
Here are a few topics , Very representative , And these topics use a lot of keywords and TS grammar
- How to judge the key value in the loop of the object
- P in keyof as any extends P What does that mean?
- If you have to use & operator , How to merge before returning & 2 Content of edges
The selected questions above , In fact, the problem-solving routines are the same , Got it 3 After a question , These questions can be solved by setting templates
00003-medium-omit Topic realization
demand : Omit Will create an ellipsis K In the field T object .
This sum Pick
It's like , It's just the opposite ,Pick Is to select the required fields , and Omit Exclude the specified field
- According to the known keywords , keyof Definitely , But how to exclude other keys ?
usenever
To make the key , You can exclude the value in this field
So the first question arises How to judge the key value in the loop of the object
First look at the answer :
type MyOmit<T, K extends keyof T> = {
[P in keyof T as P extends K ? never : P]: T[P]
}
K extends keyof T
These grammars are not explained , and Pick equally , If you don't know, you can see the first article ,TS Pre knowledge of gymnastics
The point is P extends K ? never : P
Judge P Whether this key belongs to K The scope of the , What belongs to is to be excluded , return nerver, If you don't belong to, you need to return to the current P, For keeping the current key
Seeing this leads to the second question P in keyof as any extends P What does that mean?
Add some parentheses to understand
[
(P in keyof T) as
(P extends K ? never : P)
]
With as Demarcation , Divide this code into 2 paragraph
P in keyof T
Traversal means , That's easy to understand- as Here, let's consider it as Assertion
P extends K ? never : P
Here is to judge the type
How to connect them
- P stay T Range loop
- P Get is T The key
- For this P We affirm for him by
P / never
- If P The key of is K In the range of , We will assert the current P yes never( Abandon the original P Value ), So when the object loops never Will be ignored , So as to achieve Omit
00008-medium-readonly-2 Topic explanation
demand : This is readonly Of plus edition , Specify fields to readonly, If not specified, it will be regarded as all readonly
good heavens , Just finished learning Pick and Omit, It is also the specified field , It's easy to catch , use &
Merge and you're done
Here is a demonstration of the error :
The wrong idea at that time was like this : Since it is the specified field readonly, Then I'll take it The original object and Merge the objects from the specified field loop , Loop object plus readonly, Let the following fields overwrite the previous , That won't achieve the effect
// Error model
type MyReadonly21<T, K extends keyof T = keyof T> = T & {
readonly [P in K]: T[P]
}
The result must be wrong , because &
Operator calculates intersection , To put it simply, a piece of code is
type testReadonly = {
title: string; name: string } & {
readonly title: string; name: string }
// test Will report a mistake : The prompt is missing title Field
// Property 'title' is missing in type '{ name: string; }' but required in type '{ title: string; name: string; }'.
const test: testReadonly = {
name: '111'
}
According to the truth title The merged fields should also be read-only , But he became mandatory . intersection Fine products , hold readonly Understood as a title One of the fields additional The label of
The correct answer is as follows :
use Omit Pick out the required fields , And then with Pick Pick out readonly The object of , this 2 The correct answer is to merge objects
type MyReadonly2<T, K extends keyof T = keyof T> = {
[P in keyof Omit<T, K>]: T[P]
} & {
readonly [P in K]: T[P]
}
There are also complex schemes , Just pretend I can't use Omit
, Using the routine just learned above can also solve this problem
type MyReadonly21<T, K extends keyof T = keyof T> = {
[P in keyof T as P extends K ? never : P]: T[P]
} & {
readonly [P in K]: T[P]
}
02595-medium-pickbytype Topic realization
This topic is exactly the same as the above routine !! It's also necessary to decide what to do when cycling key To keep
The difference is to filter according to the corresponding types of different fields , That is to say, before [P in keyof T as P extends U]
, Change it into [P in keyof K as T[P] extends U ? nerver : P]
Be careful T[P] extends U
Writing ! The change of such a parameter , The rest should be taken P Or take P, The never still never, The problem is solved
02757-medium-partialbykeys Topic explanation
demand : Specify fields to set optional , If it is not specified, it will be regarded as all selected
It is this problem , The questions that come out 3: If you have to use & operator , How to merge before returning & 2 Content of edges
See this problem , Is it right? readonly2
Our needs are the same , It's nothing more than putting readonly
Switch to ?
The code was written in a snap , Then look at the test cases None of them
type PartialByKeys<T, K extends keyof T = keyof T> = {
[P in keyof T as P extends K ? never : P]: T[P]
} & {
[P in K]?: T[P]
}
But watch the field carefully , What is required is required , There are ?. Except that the case gives a complete object , And mine is a {} & {}
Cross calculated , There is no difference between others
Then I studied the test cases carefully , Look for the 02757-partialbykeys The test case of this question , It's using Equal
Tool class
type cases = [
Expect<Equal<PartialByKeys<User, 'name'>, UserPartialName>>,
Expect<Equal<PartialByKeys<User, 'name' | 'unknown'>, UserPartialName>>,
Expect<Equal<PartialByKeys<User, 'name' | 'age'>, UserPartialNameAndAge>>,
Expect<Equal<PartialByKeys<User>, Partial<User>>>
]
and 08-readonl2 Test cases for , It's using Alike
:
type cases = [Expect<Alike<MyReadonly21<Todo1>, Readonly<Todo1>>>]
good heavens .. In this case , readonl2 It's not a complete standard answer , At most 98 branch ?
It is also very easy to solve this problem , We just have to take 2 Just merge them , As for how to merge ?
Another trick —— use Pick
, because Pick Can bring out all the fields , Then merge into a new object , We only need to put all our fields in and extract them once , Can merge together
type Clone<T> = Pick<T, keyof T>
type PartialByKeys<T, K extends keyof T = keyof T> = Clone<
{
[P in keyof T as P extends K ? never : P]: T[P]
} & {
[P in K]?: T[P]
}
>
Come here , The regular example has passed , And one more PartialByKeys<User, 'name' | 'unknown'>
Reporting errors
Because the second field passed in here may not be User Inside , such as unknown It's not there User Of key in , And we K extends keyof T = keyof T
This limits the entry of parameters , So we can only remove the restrictions , Change to the following
type PartialByKeys2<T, K = keyof T> = Clone<
{
[P in keyof T as P extends K ? never : P]: T[P]
} & {
[P in K]?: T[P]
}
>
After removing the restrictions , added 2 A new error report
- K The error of Type ‘K’ is not assignable to type ‘string | number | symbol’.
T[P]
The error of Type ‘P’ cannot be used to index type ‘T’.
Because there is really no limit k The type of , and in
What circulates is unio( Joint type ) The variable of T[P]
because K It doesn't have to be T The key inside ,T[‘unknown’] It certainly doesn't exist , That's why I made a mistake
So when K In the cycle , Or use it back The routine just learned , Determine the key value in the loop [P in K as P extends keyof T ? P : never]
T[P]
The solution to the problem is to judge first P Is in T Only read within the scope of T[P]
Just OK 了
The complete correct answer is as follows :
type PartialByKeys2<T, K = keyof T> = Clone<
{
[P in keyof T as P extends K ? never : P]: T[P]
} & {
[P in K as P extends keyof T ? P : never]?: P extends keyof T ? T[P] : never
}
>
Last
Let's answer a few questions
- How to judge the key value in the loop of the object
- use
as
keyword ,as Followed by conditional statements , If false, Then return to never You can exclude a key value
- use
- P in keyof as any extends P ? never : P What does that mean?
- P in keyof It's a group.
- extends P ? never : P It's a group.
- Last 2 The value of the group is as link , The key that forms the current loop
- If you have to use & operator , How to merge before returning & 2 Content of edges
- & Symbols are a process of cross merging , The merged objects are There is no difference in the function of constraint data
- But the data after cross operation and single type are used Strictly equal The result of comparison is false
- Finally, it can be based on Pick Tools , Encapsulates a Clone Tools , hold
{} & {}
Merge into one{}
边栏推荐
- Force buckle day31
- [MySQL learning notes 29] trigger
- Simple and understandable high-precision addition in C language
- Sélectionnez toutes les lignes avec un symbole dans Word et changez - les en titre
- Emo diary 1
- How can word delete English only and keep Chinese or delete Chinese and keep English
- If Jerry needs to send a large package, he needs to modify the MTU on the mobile terminal [article]
- TS 类型体操 之 循环中的键值判断,as 关键字使用
- Typescript indexable type
- C # connect to SQLite database to read content
猜你喜欢
烧录场景下的源代码防泄密方案分享
杰理之如若需要大包发送,需要手机端修改 MTU【篇】
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
The way to learn go (I) the basic introduction of go to the first HelloWorld
Go learning -- implementing generics based on reflection and empty interfaces
[MySQL learning notes 32] mvcc
Excel的相关操作
Simulation of holographic interferogram and phase reconstruction of Fourier transform based on MATLAB
You deserve this high-value open-source third-party Netease cloud music player
成为优秀的TS体操高手 之 TS 类型体操前置知识储备
随机推荐
Lesson 12 study notes 2022.02.11
Excel的相关操作
杰理之开发板上电开机,就可以手机打开 NRF 的 APP【篇】
ORACLE列转行--某字段按指定分隔符转多行
洛谷P4127 [AHOI2009]同类分布 题解
GET/POST/PUT/PATCH/DELETE含义
word中把带有某个符号的行全部选中,更改为标题
2022年Instagram运营小技巧简单讲解
navicat如何导入MySQL脚本
Simple and understandable high-precision addition in C language
Markdown 中设置图片图注
C语言 简单易懂的高精度加法
Twelve rules for naming variables
You deserve this high-value open-source third-party Netease cloud music player
杰理之BLE【篇】
Games101 Lesson 7 shading 1 Notes
[CF Gym101196-I] Waif Until Dark 网络最大流
智能终端设备加密防护的意义和措施
word设置目录
Summary of Digital IC design written examination questions (I)