TypeScript What 'string & {}' mean meaning?

Nhan Nguyen - Jun 26 - - Dev Community

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:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .