Hacker News new | ask | show | jobs
by Sirenos 1419 days ago
That's really interesting.

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

It gives a type error, because strings are not assignable to string literals.

https://www.typescriptlang.org/play?#code/FAEwpgxgNghgTmABAM...

However, if you check or assert that the returned value is one of the accepted literals, compiler accepts it:

https://www.typescriptlang.org/play?#code/FAEwpgxgNghgTmABAM...

This is one of the classic examples of flow-sensitive typing in TS.

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
    }
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.