If you ever want to create a Typescript type that provides you with autocomplete for known values but still allows any string.
You might think you can just use | string
, but this actually just “clears” the other known values.
type MyString = 'a' | 'b' | string
// ^? type MyString = string
type MyString2 = 'a' | 'b' | string & {}
// ^? type MyString = "a" | "b" | string & {}
If you try and use MyString2
, you’ll find it provides with autocomplete but allows other values.
Whereas MyString
doesn’t provide auto-complete at all.
Source
https://github.com/microsoft/TypeScript/issues/29729#issuecomment-505826972