(This code snippet is purely for demonstration purposes, as no real use-case exists here)
I am attempting to create a function that throws an error if the input string is equal to "fish". I have achieved this using the as
keyword, but I am curious if there is another way to accomplish this without relying on as
.
function throwIfFish<S extends string>(string: S): S extends "fish" ? never : S {
if (string === "fish") {
throw new Error("fish");
}
return string as S extends "fish" ? never : S;
// ^ Is there an alternative approach?
}