当前位置:网站首页>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{}
边栏推荐
猜你喜欢
navicat如何导入MySQL脚本
ORACLE列转行--某字段按指定分隔符转多行
Summary of Digital IC design written examination questions (I)
jmeter性能测试步骤实战教程
Related operations of Excel
SSM学习
Jerry's ad series MIDI function description [chapter]
Three no resumes in the software testing industry. What does the enterprise use to recruit you? Shichendahai's resume
You deserve this high-value open-source third-party Netease cloud music player
Ali's redis interview question is too difficult, isn't it? I was pressed on the ground and rubbed
随机推荐
word怎么只删除英语保留汉语或删除汉语保留英文
Word setting directory
C语言 简单易懂的高精度加法
杰理之BLE【篇】
mysql如何合并数据
TypeScript void 基础类型
杰理之开发板上电开机,就可以手机打开 NRF 的 APP【篇】
Résumé de la structure du modèle synthétisable
SSM learning
#systemverilog# 可綜合模型的結構總結
qt颜色与字符串、uint相互转换
1091: two or three things in childhood (multi instance test)
How MySQL merges data
【mysql学习笔记29】触发器
Typescript void base type
Oracle column to row -- a field is converted to multiple rows according to the specified separator
Typescript interface properties
When the Jericho development board is powered on, you can open the NRF app with your mobile phone [article]
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
TS 类型体操 之 extends,Equal,Alike 使用场景和实现对比