DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

4 2

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:

Image of Timescale

Timescale ā€“ the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (3)

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

šŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay