Today I was asked what type never
is for TypeScript, but it was confusing for me, is it just to say that it does not return anything? What's the difference to void
?
Today I was asked what type never
is for TypeScript, but it was confusing for me, is it just to say that it does not return anything? What's the difference to void
?
One of the differences is that void
means that the function ends, then never
represents that the function will remain forever until an error occurs
Examples of never
// Funcao que lança um erro
function error(message: string): never {
throw new Error(message);
}
// funcão que nunca retorna;
function infiniteLoop(): never {
while (true) {
}
}
// função que nunca retorna pois o método error retorna never
function fail(): never {
return error("Something failed");
}