Do you have a hard time dealing with typescript string literal union type?
what is string literal union type? ๐ค
As I understand it, its the way you could use string as union type. the string will be treated as โsymbolโ and will be different from normal string
It can be anything you want, and it help you to select the correct value for the variable in the typescript.
Typescript smart intellisense can provide us option when we want to put value into it. ๐
but sometimes its not perfect, like what we wanted.
like you can see, the string is not pass as the string literal type. ๐
so how you can pass it? ๐ฆ
here the secrets: ๐
We need to change our codes a a bit.
create an array that store all valid value, and make the type from it automatically. Thatโs it! The compiler wont complain anymore! ๐
Tips: its type safe guard, which mean if you donโt input the right value you will get error! better catch this error or you might get trouble in the production line!
This is different approach, that I like more, it give you ability to give a default value, instead of throwing error.
It will keep the type guard, if you set the throwError
to false, and blank the defaultValue
, it will return type โAโ | โBโ | undefined
, so you can deal with undefined
value later.
Thatโs All!
I have search this solution from months ago! Finally made it!
here I create a repo for you who interested to give feedback,
https://github.com/fatihaziz/StringLiteralEnumType/tree/main
Like always,
Good Luck, cheers! ๐ฅ
Also maybe you want to support me on Ko-Fi, or give me feedback here. All your support matters and i really appreciate it!
Thank you! ๐
Top comments (0)