In Typescript, suppose I want to call a function with following signature-
function foo(param: "TRUE"|"FALSE"|"NONE")
How can I do something like-
var str = runtimeString()
if(str === "TRUE" | str === "FALSE" | str === "NONE")
foo(str)
Or, the explicit values are the only way-
var str = runtimeString()
if(str === "TRUE")
foo("TRUE")
else if(str === "FALSE" )
foo("FALSE")
else if(str === "NONE")
foo("NONE")
Hence, you can treat a variable that has a string literal type like a variable of type string . You can access properties, call methods, and use operators, just as you would with regular strings: const eventName: "click" | "mouseover" = "click"; eventName. length; // 5 eventName.
The string literal type allows you to specify a set of possible string values for a variable, only those string values can be assigned to a variable. TypeScript throws a compile-time error if one tries to assign a value to the variable that isn't defined by the string literal type.
A string literal or anonymous string is a type of literal for the representation of a string value in the source code of a computer program.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With