DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

TypeScript What 'string & {}' mean meaning?

Give an example, we define a Color type:

type Color = "primary" | "secondary" | string;
Enter fullscreen mode Exit fullscreen mode

Then we use it like this:

const color: Color = "primary";
Enter fullscreen mode Exit fullscreen mode

But there's an issue:

Image description

We aren't getting color suggestions when we use the Color type.

We want primary and secondary to be on that list. How do we manage that?

We can intersect the string type in Color with an empty object like this:

type Color = "primary" | "secondary" | (string & {});
Enter fullscreen mode Exit fullscreen mode

Now, we'll get suggestions for primary and secondary when we use the Color type.

Image description


I hope you found it helpful. Thanks for reading. ๐Ÿ™

Let's get connected! You can find me on:

Top comments (4)

Collapse
 
mikhaelesa profile image
Mikhael Esa

Can you explain what does type Color = "primary" | "secondary" | (string & {}); has to offer compared to the basic intersection type Color = "primary" | "secondary";

Because the basic intersection can already give the suggestion.

Collapse
 
nhannguyenuri profile image
Nhan Nguyen

I want "primary", and "secondary" to appear in the suggestion list. And other strings should be accepted:

Image description

Collapse
 
dscheglov profile image
Dmytro Shchehlov

@nhannguyendevjs
DX is a great thing, but sometimes we read code without intellisence.
So the code

type Color = "primary" | "secondar" | (string & {});
Enter fullscreen mode Exit fullscreen mode

confuses too much.

Collapse
 
cebulon profile image
Thomas Schroeder • Edited

There is no explanation WHY this is working. That is why I was here.

ChatGPT to the rescue:

When a union type in TypeScript includes both specific string literals (e.g., 'red' | 'blue') and the general string type (e.g., 'red' | 'blue' | string), TypeScript's type inference often simplifies the union to just string. This simplification can lead to a loss of autocomplete suggestions for the specific literal values.

The (string & {}) construct prevents this simplification. By intersecting string with an empty object literal type ({}), TypeScript treats the resulting type as a distinct entity that does not collapse into a plain string when part of a union with string literals.