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)