DEV Community

Advanced TypeScript Exercises - Question 1

Pragmatic Maciej on February 06, 2020

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<Exa...
Collapse
 
mateiadrielrafael profile image
Matei Adriel • Edited

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)

Collapse
 
avfirsov profile image
Andrew Firsov

Nice challenge :) Here are 2 solutions

Collapse
 
macsikora profile image
Pragmatic Maciej

You are really picky :). I hope in the series I will put some questions which will satisfy you. Thanks for feedback.

Collapse
 
mateiadrielrafael profile image
Matei Adriel

Np, check the edit to the original comment to see a challenge idea

Thread Thread
 
macsikora profile image
Pragmatic Maciej

Nice one. Thank you!

Collapse
 
gillchristian profile image
Christian Gill • Edited

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.

Collapse
 
macsikora profile image
Pragmatic Maciej

Niiice :D

Collapse
 
mateiadrielrafael profile image
Matei Adriel

Yep, it's sad to see typescript missing so much from not having higher kinded types!

Collapse
 
jopie64 profile image
Johan

Can be simulated a bit though...

Thread Thread
 
mateiadrielrafael profile image
Matei Adriel

Wow, I was only familiar with the approach fp-ts took, its nice to see cool stuff like this:)

Collapse
 
gillchristian profile image
Christian Gill

We can do a lot already, right? But yeah, it'd be nice to have.

Collapse
 
nmonastyrskyi profile image
Nikita Monastyrskiy

I'm happy, I found your exercises! They are absolutely useful, exectly what I was looking for. A lot of thanks!

Collapse
 
dwjohnston profile image
David Johnston

Ah, so this is where the infer keyword is useful:

type Transform<A> = A extends Promise<infer T> ? T : never; 
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
herrschade profile image
Oskar • Edited

This is mine. Nothing special :)

type Transform<A> = Awaited<Promise<A>>

Collapse
 
sergei_tiulenev_27bd5d09c profile image
Sergei Tiulenev
Collapse
 
mayunike profile image
mayunike