Type never - TypeScript

2

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 ?

    
asked by anonymous 18.05.2018 / 14:17

1 answer

1

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");
}
    
18.05.2018 / 14:26