What is the difference between void and never types in Typescript ?
While both void and never types in TypeScript represent the absence of a meaningful return value, they have distinct purposes and behaviors:
1. void:
Used to indicate functions that do not return a value explicitly. These functions typically perform actions like logging, modifying data, or throwing errors.
The implicit return type of such functions is void. You can also explicitly specify void as the return type.
Functions with a void return type cannot be assigned to variables of other types, unlike functions with any or any other returning type.
Example:
TypeScript
function logMessage(message: string): void {
console.log(message);
}
// Compiler error: Type 'void' is not assignable to type 'string'
// let result = logMessage("Hello!");
2. never:
Used to represent functions that never normally return. This could be because they throw an error, enter an infinite loop, or have unreachable code paths.
Assigning never to a variable implies that the code will not reach that point normally.
Functions with a never return type cannot be used in many contexts, like being assigned to variables, used in conditional statements, or passed as function arguments. This ensures type safety by preventing unexpected usage.
Example:
TypeScript
function throwError(message: string): never {
throw new Error(message);
}
// Function cannot be assigned to a variable
// let result: string = throwError("Oops!");
// Function argument type mismatch
// someFunction(throwError("Something went wrong"));
Key Differences:
In summary:
Use void for functions that don't return a value but might complete normally.
Use never for functions that definitely never return normally due to errors, loops, or unreachable code.
By understanding their differences, you can choose the appropriate type to accurately represent the behavior of your functions and enhance type safety in your TypeScript code.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.