The void
And never
Types
void
In TypeScript, the “void” type is a type that represents the absence of a value. It is commonly used for function return types to indicate that the function does not return a value.
For example, here is a function that has a return type of “void”:
function printMessage(message: string): void {
console.log(message);
}
In this example, the
printMessage
function takes in a string as a parameter and logs it to the console, but it does not return a value. Therefore, its return type is “void”.The “void” type can also be used for variables that are never assigned a value. For example:
let myVariable: void;
In this example, the
myVariable
variable is declared with the “void” type, but it is not assigned a value. This is allowed because the “void” type represents the absence of a value, but it is generally not considered good practice to declare variables without assigning them a value.The “void” type is useful for indicating that a function does not return a value, but it should not be used for variables that are intended to hold a value. Even if you will not be assigning a value when you declare it, you should type it accordingly to the value it will receive in the future.
never
The
never
type represents the type of values that never occur. This is a type that can be used in the return type of functions that always throw an exception or never return. For example:function error(message: string): never {
throw new Error(message);
}
In this example, the
error
function has a return type of never
because it always throws an exception and never returns a value.Another use for the
never
type is in the type of variables or properties that are never reassigned. For example:const a: never = error("Something went wrong");
In this example, the type of the
a
variable is inferred to be never
because it is assigned the return value of the error
function, which has a return type of never
.Here is another example of a function that has a return type of
never
:function infiniteLoop(): never {
while (true) {
// Do something...
}
}
In this example, the
infiniteLoop
function has a return type of never
because it contains an infinite loop and never returns a value.