Member-only story
TypeScript : Understanding void
and unknown
TypeScript offers several types to ensure your code is safe and predictable. Among them, void
and unknown
are two unique types that serve specific purposes. This post will help you understand these types, their use cases, and how to implement them with examples.
Q1: What is the
void
Type?
The void
type represents the absence of a value. It is most commonly used as the return type for functions that don’t return anything. If a function performs a side effect (e.g., logging something or modifying data) but doesn't produce a result, its return type should be void
.
Key Points About void
:
void
indicates that the function does not return a value.- Attempting to assign a
void
function to a variable will result in aundefined
value, asundefined
is the actual return value in JavaScript.
Example: Function with void
Type:
function logMessage(message: string): void {
console.log(`Log: ${message}`);
}
logMessage("Hello, TypeScript!"); // Output: Log: Hello, TypeScript!
Explanation:
- The
logMessage
function doesn’t return anything. Its purpose is to log a message, so the return type isvoid
. - If you attempt to use the return value of this function (e.g…