If we have a type which is wrapped type like Promise
. How we can get a type which is inside the wrapped type? For example if we have Promise<ExampleType>
how to get ExampleType
?
Take a look at below code. Write an utility type Transform
which will take a generic type argument, and if it is a Promise
it will evaluate to the type inside it.
type X = Promise<string>
type Y = Promise<{ field: number }>
type ResultX = Transform<X>; // ResultX type equals string
type ResultY = Transform<Y>; // ResultY type equals { field: number }
type Transform<A> = /** here your answer **/
Post your answers in comments. Have fun! Answer will be published soon!
If you are interested in notifications about next articles please follow me on dev.to and twitter.
Top comments (16)
Nice little challenge, I wouldnt call it advanced tho, maybe more like intermediate?
Edit: heres another challenge: make a type Reverse which takes a tuple of any length and reverses its elements! (Hint: use the
{ 0: A; 1: B }[C extends D ? 0 : 1]
hack to be able to use recursion in some cases where typescript woule've thrown an error)Nice challenge :) Here are 2 solutions
You are really picky :). I hope in the series I will put some questions which will satisfy you. Thanks for feedback.
Np, check the edit to the original comment to see a challenge idea
Nice one. Thank you!
Playground link. To avoid spoilers.
(On the phone so I re-wrote the example with Array)
I think the wrapper type cannot be generic. I mean the same solution wouldn't work for Promise and Array. Or at least I don't know a way.
Niiice :D
Yep, it's sad to see typescript missing so much from not having higher kinded types!
Can be simulated a bit though...
Wow, I was only familiar with the approach fp-ts took, its nice to see cool stuff like this:)
We can do a lot already, right? But yeah, it'd be nice to have.
I'm happy, I found your exercises! They are absolutely useful, exectly what I was looking for. A lot of thanks!
Ah, so this is where the
infer
keyword is useful:Basically, the
infer
keyword here lets us start referencing a new type, that didn't come from the original type declaration. In this case - we are returning it.This is mine. Nothing special :)
type Transform<A> = Awaited<Promise<A>>
type Transform = A extends Promise ? R : A;
dev-to-uploads.s3.amazonaws.com/up...