InterviewSolution
| 1. |
Explain the purpose of the never type in TypeScript. |
|
Answer» As the name suggests, the never type represents the type of values that never occur. For example, a function that never RETURNS a value or that always throws an exception can mark its return type as never. function error(message: string): never {throw new Error(message);}You might wonder why we need a ‘never’ type when we ALREADY have ‘void’. Though both types look similar, they represent two very different concepts. A function that doesn't return a value implicitly returns the value undefined in JAVASCRIPT. Hence, even though we are saying it’s not returning anything, it’s returning ‘undefined’. We usually ignore the return value in these cases. Such a function is inferred to have a void return type in TypeScript. // This function returns undefinedfunction greet(name: string) {console.log(`Hello, ${name}`);}let greeting = greet("David");console.log(greeting); // undefinedIn contrast, a function that has a never return type never returns. It doesn't return undefined, either. There are 2 cases where functions should return never type: |
|