TypeScript What ‘string & {}’ mean meaning?

Give an example, we define a Color type:

type Color = “primary” | “secondary” | string;

Then we use it like this:

const color: Color = “primary”;

But there’s an issue:

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


This content originally appeared on DEV Community and was authored by Nhan Nguyen

Give an example, we define a Color type:

type Color = "primary" | "secondary" | string;

Then we use it like this:

const color: Color = "primary";

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 & {});

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:


This content originally appeared on DEV Community and was authored by Nhan Nguyen


Print Share Comment Cite Upload Translate Updates
APA

Nhan Nguyen | Sciencx (2024-06-26T09:37:46+00:00) TypeScript What ‘string & {}’ mean meaning?. Retrieved from https://www.scien.cx/2024/06/26/typescript-what-string-mean-meaning/

MLA
" » TypeScript What ‘string & {}’ mean meaning?." Nhan Nguyen | Sciencx - Wednesday June 26, 2024, https://www.scien.cx/2024/06/26/typescript-what-string-mean-meaning/
HARVARD
Nhan Nguyen | Sciencx Wednesday June 26, 2024 » TypeScript What ‘string & {}’ mean meaning?., viewed ,<https://www.scien.cx/2024/06/26/typescript-what-string-mean-meaning/>
VANCOUVER
Nhan Nguyen | Sciencx - » TypeScript What ‘string & {}’ mean meaning?. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/26/typescript-what-string-mean-meaning/
CHICAGO
" » TypeScript What ‘string & {}’ mean meaning?." Nhan Nguyen | Sciencx - Accessed . https://www.scien.cx/2024/06/26/typescript-what-string-mean-meaning/
IEEE
" » TypeScript What ‘string & {}’ mean meaning?." Nhan Nguyen | Sciencx [Online]. Available: https://www.scien.cx/2024/06/26/typescript-what-string-mean-meaning/. [Accessed: ]
rf:citation
» TypeScript What ‘string & {}’ mean meaning? | Nhan Nguyen | Sciencx | https://www.scien.cx/2024/06/26/typescript-what-string-mean-meaning/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.