Marcus Riemer Marcus Riemer - 1 year ago 66
TypeScript Question

Checking validity of string literal union type at runtime?

I have a simple union type of string literals and need to check it's validity because of FFI calls to "normal" Javascript. Is there a way to ensure that a certain variable is an instance of any of those literal strings at runtime? Something along the lines of

type MyStrings = "A" | "B" | "C";
MyStrings.isAssignable("A"); // true
MyStrings.isAssignable("D"); // false

Answer Source

using type is just Type Aliasing and it will not be present in the compiled javascript code, because of that you can not really do:

MyStrings.isAssignable("A");

What you can do with it:

type MyStrings = "A" | "B" | "C";

let myString: MyStrings = getString();
switch (myString) {
    case "A":
        ...
        break;

    case "B":
        ...
        break;

    case "C":
        ...
        break;

    default:
        throw new Error("can only receive A, B or C")
}

As for you question about isAssignable, you can:

function isAssignable(str: MyStrings): boolean {
    return str === "A" || str === "B" || str === "C";
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download