Issue
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?
Solution
There are some use cases of "Never" keyword in Typescript.
The never type is used when you are sure that something is never going to occur.
✅ Guard Clauses: it forces you to check all possible cases.
✅ Function will never return anything. It has something to do all the time (infinitive loop)
✅ Function always Throws Error.
// 1) Guard Clauses (forces you to check all possible cases)
type CurrencyOptions = "EURO" | "USD" | "AZN"
function getRate(currency: CurrencyOptions) {
switch (currency) {
case "EURO":
return 1.80
case "USD":
return 1.70
case "AZN":
return 1.20
default:
const _unreachable: never = currency // will get Type Error if you remove one of the cases
throw "Not found"
}
}
// 2) function will Throw error
function throwError(errorMsg: string): void {
throw new Error(errorMsg);
}
// 3) function will Never end
function keepProcessing(): never {
while (true) console.log('Never ends.')
}
Main difference between never and void is that:
Void - function doesn't return anything or explicitly returns undefined.
Never - function never returns anything at all.
Answered By - NazarPasha
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.