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. ๐Ÿ˜Š

@mattpocockuk: Time to talk about one of the ...

@mattpocockuk
7 views Aug 16, 2024
1
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 ๐Ÿงต
Media image
2
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:
Media image
3
Then, using that type in your `Icon` component:
Media image
4
Then, you might use the `Icon` component like this:
Media image
5
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?
6
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?
Media image
7
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:
Media image
8
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.
Media image
9
Now, when we use `Color`, TypeScript will remember that `"primary"` and `"secondary"` are part of the type - and it'll give us suggestions accordingly.
10
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.
11
Less that 10% of folks get to the end of these threads.

You're a special bugger. Join the club:

totaltypescript.com/newsletter
Actions
Visual Editor Carousel Maker NEW
Update Thread
What You Can Do
  • Download as PDF
  • Save to Notion
  • Export as Markdown
  • Visual Editor
  • LinkedIn & Instagram Carousel Maker
Create Free Account

Includes 7-day Premium trial