32

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")

4 Answers 4

15

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);
Sign up to request clarification or add additional context in comments.

1 Comment

The extra function is not needed; <NullableBoolean>str alone works as well
14

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.

Comments

10

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.

3 Comments

You can make an array of values, and define the type and function based on the array to avoid the repetition.
@MarkSwardstrom How can I define a type based on an array?
@HAlves I added an answer so it would format
3

@SimonBergot has the answer above, but this is a way to avoid the repetition in the array

const nullableBooleanValues = ["TRUE", "FALSE", "NONE"] as const;

type NullableBoolean = typeof nullableBooleanValues[number];

const isNullableBoolean = (value: unknown): value is NullableBoolean =>
  nullableBooleanValues.includes(value as NullableBoolean);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.