Idlliofrio Idlliofrio - 2 months ago 9
TypeScript Question

Never datatype in Typescript

I have been going through the documentation of Typescript and came across the datatype Never, so far I couldn't exactly figure out what they are trying to imply in the sentence ,
// Function returning never must have unreachable end point

function infiniteLoop(): never {
while (true) {
}
}


Can anyone explain this to me?

Answer

It says that if specify never as the return type, the return statement of the function must not be reachable. For example the function will always throw an error, or there's an infinite loop somewhere.

It's easily to visualize this if we rewrite the example like this:

function infiniteLoop(): never {
    while (true) {
    }
    return 'this will never execute';
}