Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit of never in typescript

Tags:

typescript

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?

like image 501
Sunil Garg Avatar asked Jul 12 '17 12:07

Sunil Garg


1 Answers

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
    }
};
like image 133
Rodris Avatar answered Nov 15 '22 03:11

Rodris