You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
However, one day I saw another usage of infer like this
typeGetTypeVal2<T>={type: T}|T|{typeName: T}typeTypeVal21={type: string}extendsGetTypeVal2<infer T> ? T : any//stringtypeTypeVal22={type: string,typeName: number}extendsGetTypeVal2<infer T> ? T : any//string | number
It describes the situations first and then uses the infer as the generic params to get the matched types. A little different from GetTypeVal1. Also, we can change GetTypeVal1 to work like GetTypeVal2.
How to use recursion
Add generic params to pass recursive params.
Example:
How to count for Array
Use the
length
of theArray
instance. Examples:How to transform
number
tostring
Use the template literal and
infer
.Example: Absolute
How to transform
string
tonumber
Use
string
to compare andArray
to count.Example:
How to access some parts of string or Array
Use multiple
infer
keywords.Example: StringToUnion
How to detect if a string or input value needs transformation
Compare the input with the output using
extends
.Example:
How to add transformation except for the first time
Set default value in generic params.
Example:
How to test every item type in
Array
likesome
andevery
?Use
Array[number]
.Example:
infer
match modeinfer
as generic paramsNormally, we would use
infer
likeHowever, one day I saw another usage of
infer
like thisIt describes the situations first and then uses the
infer
as the generic params to get the matched types. A little different fromGetTypeVal1
. Also, we can changeGetTypeVal1
to work likeGetTypeVal2
.Compared with
infer
in generic params, wouldn't that easier?However, normally this is not what we want. Also, there is a related problem to look out for. microsoft/TypeScript#32389
How to add properties to an object, items to an array, or union recursively?
Utilities
The text was updated successfully, but these errors were encountered: