HomeAboutBlog

Typescript Void & Never Types

January 16, 2024

TypeScript introduces powerful features that enhance clarity and structure in your code. Among these, the void and never types take center stage, each playing a crucial role in signaling the absence of a type and representing values that can never occur. Let's unravel their mysteries.

The Whisper of void

void steps into the spotlight to symbolize the absence of any type, often indicating that a function doesn't return anything. Consider the following scenario:

function logMessage(message: string): void {
  console.log(message);
}

const result: void = logMessage("Hello, TypeScript!"); // const result: void;

In this case, logMessage fulfills its duty without the expectation of a return value. Annotating callback functions that don't return is another common use of void:

function executeCallback(callback: () => void): void {
  // implementation goes here
}

Additionally, annotating the return type of functions with void when you're certain they won't return anything is a good practice. TypeScript then acts as a vigilant guardian, warning you if you inadvertently attempt to return something.

function noReturnValue(): void {
  // implementation with no return
}

However, using void outside the context of function return values proves unhelpful, as you can't assign anything to void variables. Stick to employing it with functions that truly return nothing.

The Enigma of never

Embracing the Unattainable

Now, let's shift our focus to never. Imagine functions that go beyond not returning anything; they can never return anything.

function throwError(): never {
  throw new Error("Something went wrong!");
}

const result: never = throwError();
// const result: never;

function loopForever(): never {
  while (true) {}
}

const loopResult: never = loopForever();
// const loopResult: never;

Unlike void, which denotes the absence of a type, never signifies a type that will never exist at runtime. If you attempt to access or modify a never variable, TypeScript will promptly raise a warning.

In most cases, you need to explicitly annotate a function with the never type. However, there's a special case where TypeScript correctly infers the return type as never: returning the results of a never function.

function implicitNever(): never {
  return throwError();
}
const result: never = implicitNever();
// const result: never;

Expect to encounter never again when exploring Intersection types and Conditional types in TypeScript. Always keep in mind that never represents a type associated with values that will never manifest during runtime.

In the captivating world of TypeScript, void and never play distinctive roles, adding depth and precision to your type annotations. Embrace their nuances, and wield them wisely in your coding endeavors! 🚀🧠

Related posts: