DEV Community

Cover image for String Literal Union Type with TypeGuard in Typescript
Fatih Aziz
Fatih Aziz

Posted on

String Literal Union Type with TypeGuard in Typescript

Do you have a hard time dealing with typescript string literal union type?
what is string literal union type? πŸ€”

string-literal-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.

type-autocomplete

Typescript smart intellisense can provide us option when we want to put value into it. 😎

but sometimes its not perfect, like what we wanted.

string-literal-type-error

like you can see, the string is not pass as the string literal type. πŸ’€
so how you can pass it? πŸ“¦

here the secrets: 😎

union-type-function

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.

another-approach-type-union

It will keep the type guard, if you set the throwErrorto false, and blank the defaultValue, it will return type β€œA” | β€œB” | undefined, so you can deal with undefinedvalue 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! 😁

Oldest comments (0)