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.
paavohtl|3 years ago
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.
phpnode|3 years ago
moron4hire|3 years ago