top | item 32262912

(no title)

Sirenos | 3 years ago

That's really interesting.

    doTheThing(readFromUser())
What does the compiler do in cases where you have strings coming in like this?

discuss

order

phpnode|3 years ago

it'll tell you that `string` cannot be assigned to type `"RED" | "GREEN"`, and so you'll need to write a function that refines the type correctly, e.g.

    function isValidInput(input: unknown): input is "RED" | "GREEN" {
      return input === "RED" || input === "GREEN";
    }

    const input = readFromUser();
    if (isValidInput(input)) {
      doTheThing(input); // no type error
    }

moron4hire|3 years ago

It's an error, as the plain `string` type doesn't satisfy the union. You'll need to perform type assertions to make the return type down before passing it as a parameter.