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! ๐Ÿ˜

Top comments (0)