Hi,๐Ÿ‘‹ we have updated the app and fixed multiple bugs. We are lacking funds, request to free user not to use Adblock. Ads are non intrusive. ๐Ÿ˜Š

โœจ Visual Editor

close

palette Canvas & Background

Gradient:arrow_forward
Text Color:
135ยฐ

style Card Style

40px
16px

text_fields Typography

16px
Matt Pocock
@mattpocockuk
Time to talk about one of the strangest TypeScript tricks around.

It's the loose autocomplete trick. And it's ACTUALLY USEFUL for app development.

Let me explain ๐Ÿงต
Thread image
Matt Pocock
@mattpocockuk
Imagine you're building an `Icon` component.

Your brand has some known colors, like `primary` and `secondary`. But you also want to make sure that users can specify any color they want.

You might start by defining a `Color` type:
Thread image
Matt Pocock
@mattpocockuk
Then, using that type in your `Icon` component:
Thread image
Matt Pocock
@mattpocockuk
Then, you might use the `Icon` component like this:
Thread image
Matt Pocock
@mattpocockuk
But there's an issue. We aren't getting `color` suggestions when we use the `Icon` component. If we try to autocomplete the `color` prop, we get no suggestions.

Ideally, we want `primary` and `secondary` to be part of that list. How do we manage that?
Matt Pocock
@mattpocockuk
The solution is very odd-looking. We can intersect the `string` type in `Color` with an empty object:

Now, we'll get suggestions for `primary` and `secondary` when we use the `Icon` component.

What on earth?
Thread image
Matt Pocock
@mattpocockuk
This works because of a quirk of the TypeScript compiler.

When you create a union between a string literal type and `string`, TypeScript will eagerly widen the type to `string`. We can see this by hovering over `Color` without the intersection:
Thread image
Matt Pocock
@mattpocockuk
So, before it's ever used, TypeScript has already forgotten that `"primary"` and `"secondary"` were ever part of the type.

But by intersecting `string` with an empty object, we trick TypeScript into retaining the string literal types for a bit longer.
Thread image
Matt Pocock
@mattpocockuk
Now, when we use `Color`, TypeScript will remember that `"primary"` and `"secondary"` are part of the type - and it'll give us suggestions accordingly.
Matt Pocock
@mattpocockuk
This might feel pretty fragile to you. This doesn't seem like intended behavior from TypeScript.

Well, the team actually know about this trick. They test against it.

And someday, they may make it so that a plain `string` type will just work. But until then, keep this in mind.
Matt Pocock
@mattpocockuk
Less that 10% of folks get to the end of these threads.

You're a special bugger. Join the club:

totaltypescript.com/newsletter
Generated by Thread Navigator
100%
view_carousel Carousel Studio NEW
Press โŒ˜ + S to quick-export