Home > front end >  Typescript weird type intersection of `string & {}`
Typescript weird type intersection of `string & {}`

Time:11-02

on some libs, I often see a TS syntax something like this:

type AriaRole = | 'alert' | 'tree' | 'treegrid' | 'treeitem' | (string & {});

What the mean of string & {}?
It's a string intersected with an object.
Does that make sense or maybe a hack?

CodePudding user response:

It looks strange, because this type is basically string.

But if you wrote 'alert' | 'tree' | 'treegrid' | 'treeitem' | string then your type would be simplified to just string. This would mean if you start writing this code:

let role: AriaRole = 'a

Then you wouldn't necessarily get useful autocomplete suggestions. As far as Typescript is concerned, AriaRole would be string so you'd just be writing any string, Typescript wouldn't know that these specific strings would be worth suggesting.

But written with string & {}, it doesn't get simplified to string and so the whole union doesn't get simplified, and the consequence is that you get autocomplete suggestions for 'alert', 'tree' or so on, while also allowing any other string value.

So the reason for writing the type this way, I think, is to have a type where every string is allowed, but some strings are "encouraged" by autocomplete suggestions. It also means you can see those "encouraged" strings when you hover over the type name.

CodePudding user response:

To @AlekseyL & @kaya3

So this is the implementation of (string & {}):

type Theme = 'primary'|'secondary'|'success'|'danger'|(string & {})

interface MyComponentProps {
   theme? : Theme
}
export default function MyComponent(props: MyComponentProps) => ....

<MyComponent theme='primary' />    // choose from the pre defined themes
<MyComponent theme='customDark' /> // or use a custom theme name
  • Related