In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shows you how conditional type intensive reading and practice recording are in TypeScript. The content is concise and easy to understand. It will definitely make your eyes shine. I hope you can gain something through the detailed introduction of this article.
In most programs, we have to make decisions based on input. TypeScript is no exception, and conditional types are used to describe the relationship between input types and output types.
Extensions used in conditional judgments
When extended is used to express conditional judgment, the following rules can be summarized
If the types on both sides of extensions are the same, then extensions can be interpreted semantically as ===, as shown in the following example:
type result1 ='a' extends 'abc'? true: false//falsetype result2 = 123 extends 1? true: false //false
If the type to the right of extends contains the type to the left of extends (i.e. narrow type extends broad type), the result is true, otherwise it is false. See the following example:
type result3 = string extends string| number? true: false//true
When extends is applied to an object, the more keys specified in the object, the narrower the scope of its type definition. See the following example:
type result 4 ={a: true, b: false} extends {a: true}? true: false//true Use conditional types in generic types
Consider the following Demo type definitions:
type Demo = T extends U? never: T
Combined with the extensions used in conditional judgment, we know 'a'|'b'|'c' extends 'a' is false, so Demo results in 'a'|'b'|'c'?
Check out the official website, which mentions:
When conditional types act on a generic type, they become distributive when given a union type.
That is, union types are split when conditional types are applied to generic types. That is, Demo is split into 'a' extends 'a',' b 'extends' a', and 'c' extends 'a'. In pseudocode, this is similar to:
function Demo (T, U){return www.example.com (val =>{T.map return 'never'})} Demo (['a','b',' c'],'a')//['never','b',' c'] Also according to the definition of never type--never type can be assigned to each type, but no type can be assigned to never (except never itself). 'b'
'c' is equivalent to 'b'|'c'。|So the result of Demo is not an 'a'|'b'
'c' instead of 'b'|'c'。|tool type| Careful readers may have discovered that the Demo declaration process is actually an implementation of the Exclude utility type provided by TypeScript, which is used to exclude the union type ExcludedUnion from the Type type.
type T = Demo//T: 'b'
'c'
Based on the Demo type definition, it is further possible to implement Omit in the official tool type for removing the object Type| Property values that satisfy the type keys in.
type Omit ={[P in Demo]: Type
} interface Todo {title: string; description: string; completed: boolean;} type T = Omit//T: {title: string; completed: boolean} Escape
If you want Demo to result in 'a'
'b'
Can 'c' be realized? According to the official website description:| Typically, distributivity is the desired behavior. To avoid that behavior, you can surround each side of the extends keyword with square brackets.| If you don't want to traverse every type in a generic, you can enclose the generic in square brackets to indicate that you use the entire part of the generic.
type Demo =[T] extends [U]? never: T
type Demo =[T] extends [U]? never: T//result In this case type is 'a'
'b'
'c' type result = Demo Use conditional types in arrow functions| When using ternary expressions in arrow functions, the left-to-right reading habit causes the function content area to be confusing if it is not bracketed. For example, is x a function type or a Boolean type in the code below?|//The intent is not clear. var x = a => 1? true: false
In the eslint rule no-confusing-arrow, it is recommended to write as follows:
var x = a =>(1? true: false)
In TypeScript's type definition, the same is true if you use extends in arrow functions. Due to the habit of reading from left to right, it will also cause readers to be confused about the execution order of type code.
type Curry =(arg: Head
)=> HasTail
extends true? Curry: R
Therefore, it is recommended to add parentheses to the arrow function, which is very helpful for code review.
type Curry =(arg: Head
)=>(HasTail
extends true? Curry: R) Combines type derivations using conditional types
In TypeScript, type inference infer syntax is generally used in conjunction with extensions. It can be used for the purpose of automatic type inference. For example, it can be used to implement the tool type ReturnType, which is used to return the return type of the function Type.
type ReturnType = T extends (... args: any)=> infer U? U: never
type ReturnType = T extends (... args: any)=> infer U? U: neverMyReturnType string>
//stringMyReturnType Promise//Promise
The Pop, Shift, Reverse tool types associated with arrays can also be implemented by combining extensions with type derivation. Pop:
type Pop = T extends [... infer ExceptLast, any]? ExceptLast: nevertype T = Pop//T: [3, 2]
Shift:
type Shift = T extends [infer_,... infer O]? O: nevertype T = Shift//T: [2, 1]
Reverse
type Reverse = T extends [infer F,... infer Others]?[... Reverse, F]:[] type T = Reverse//T: ['b',' a'] Use conditional types to determine that two types are exactly equal
We can also use conditional types to determine whether types A and B are exactly equal. There are two main schemes in the current community:
Option 1: Refer to issue.
export type Equal1 =[T] extends [S]?(
[S] extends [T]? true: false): false
The only drawback of the current scheme is that it equates any type with any other type. type T = Equal1//T: true
Option 2: Refer to issue.
export type Equal2 =(()=> T extends X? 1:2) extends (()=> U extends Y? 1:2)? true: false
The only drawback to the current scheme is a slight flaw in the handling of crossover types.
type T = Equal2//false
The above two kinds of judgment type equal method have different opinions, the author throws a brick to attract jade here.
The above content is what the conditional type intensive reading and practice records in TypeScript are like. Have you learned knowledge or skills? If you want to learn more skills or enrich your knowledge reserves, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.