TypeScript Void and Never Types
`void` and `never` are special types in TypeScript, commonly used for different purposes. These types help describe the behavior and return values of functions.
What is the Void Type?
`void` is used to indicate that a function does not return any value. It is typically used for functions with side effects, such as logging to the console.
function logMessage(message: string): void {
console.log(message);
}
This function does not return any value—it simply logs a message. If a return type other than `void` is specified, TypeScript will expect a return value and throw an error if none is provided.
What is the Never Type?
`never` represents functions or operations that never complete normally. For example, infinite loops or functions that throw errors use the `never` type.
function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {
// Sonsuz döngü
}
}
The `never` type guarantees that a function never returns. It plays an important role in error handling and control flow analysis.
Differences Between Void and Never
`void` indicates that a function has no return value, whereas `never` means the function will never return at all. `void` functions complete execution without returning a value; `never` functions either throw errors or never terminate.
Practical Example: Throwing Errors vs. Logging
function handleError(errorMsg: string): never {
throw new Error(errorMsg);
}
function infoLog(info: string): void {
console.log("Info:", info);
}
In this example, `handleError` throws an error and never returns, so its return type is `never`. On the other hand, `infoLog` just logs information and doesn’t return anything, making its return type `void`.
Back