Exploring the latest features in TypeScript 2.0, I came across the never
type. It appears to be a clever method for defining the type of functions that do not have a return value.
If I understand correctly, the never
type can be assigned to any other type, but only never
itself can be assigned to never
. While experimenting with a simple test in VS Code, I encountered the following scenario:
function generateError(){
throw new Error("oops");
}
function do(option: "opt1" | "opt2"){
if(option === "opt1") return true;
if(option === "opt2 ) return false;
generateError();
}
let res = do("blah");
What type is expected for res
? The compiler indicates string | undefined
, which does make sense although I initially anticipated just string
. I wonder about the necessity of introducing a new type solely for functions that never return. Is this concept truly essential? Or is it primarily a tool for the compiler to enhance flow analysis?