I have just started with typescript and read about the type never. But I did not get the actual purpose of it. From this
I got, any code that is not going to execute or unreachable is marked as never
// Type () => never
const sing = function() {
while (true) {
console.log("Never gonna give you up");
console.log("Never gonna let you down");
console.log("Never gonna run around and desert you");
console.log("Never gonna make you cry");
console.log("Never gonna say goodbye");
console.log("Never gonna tell a lie and hurt you");
}
};
The function in above code has an infinite loop so that will be marked as never, so what is the benefit of this?
For your example, the benefit is to guarantee that you wont create a escape from your function.
Try to explicitly set the never
return type.
const sing = function():never {
while (true) {
console.log("Never gonna give you up");
console.log("Never gonna let you down");
console.log("Never gonna run around and desert you");
console.log("Never gonna make you cry");
console.log("Never gonna say goodbye");
console.log("Never gonna tell a lie and hurt you");
break; // Error
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With