loading...

Advanced TypeScript Exercises - Question 1

macsikora profile image Maciej Sikora ・1 min read

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.

Discussion

pic
Editor guide
Collapse
mateiadrielrafael profile image
Matei Adriel

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
Collapse
macsikora profile image
Maciej Sikora Author

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
Maciej Sikora Author

Nice one. Thank you!

Collapse
gillchristian profile image
Christian Gill

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
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
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.