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)