How to cast a String variable to a String Literal Type in Typescript How to cast a String variable to a String Literal Type in Typescript typescript typescript

How to cast a String variable to a String Literal Type in Typescript


Create a string literal type as follows:

type NullableBoolean = "TRUE" | "FALSE" | "NONE";

In the function definition, use this type for param:

function foo(param: NullableBoolean){    ...}

Make sure to cast the string to the string literal type:

var str = runtimeString();if(str === "TRUE" || str === "FALSE" || str === "NONE")    foo(<NullableBoolean>str);


If you are sure that the runtime string is of one of the valid options, you can just cast your string to the type of your function that expects the string literal type.

type Tristate =  "TRUE"|"FALSE"|"NONE";function foo(param: Tristate) {    return "enhanced: " + param;}let validInput = "NONE";foo(validInput as Tristate);

Another way to do your cast is by prepending the type like so:

foo(<Tristate> validInput);

Be aware that you override the compiler's opinion about the data in your runtime string. So at runtime there is the possibility that a value other than the defined three strings will get into your foo function.


The best way I found was to create a type guard

type NullableBoolean = "TRUE" | "FALSE" | "NONE";function foo(param: NullableBoolean){    ...}function isNullableBool(str: string): str is NullableBoolean{    return str === "TRUE" || str === "FALSE" || str === "NONE"}if(isNullableBool(str)) { foo(str); }

This is not ideal because you have to repeat the list of values but you get a better encapsulation than with Brett's answer.