Introduction to any, unknown, and never
TypeScript provides special types for situations where a value does not fit a straightforward, known type. Three important types are any, unknown, and never. Although their names may seem related, they serve very different purposes.
The any type allows a value to be used with minimal static type checking. The unknown type represents a value whose actual type has not yet been established and requires appropriate checks before type-specific operations are performed. The never type represents values that cannot occur in a particular type context, commonly appearing in functions that never complete normally or in exhaustive checks.
Understanding these types is important when working with external data, legacy JavaScript, error handling, generic utilities, and complex application states. Choosing the correct type helps preserve TypeScript's benefits instead of accidentally bypassing its type system.
1. Understanding the any Type
The any type disables most static type checking for a particular value. It allows the value to be reassigned to different types and permits operations without requiring TypeScript to verify that those operations are safe.
let value: any = 10;
value = "TypeScript";
value = true;
value = { course: "TypeScript" };
console.log(value.course);
The variable value can hold a number, a string, a Boolean, or an object because it is declared as any. TypeScript also permits the property access in the last line without verifying that every possible value assigned to value has a course property.
This flexibility can be useful when migrating JavaScript code to TypeScript, integrating with an untyped library, or temporarily working around an unavailable type definition. However, it can also hide bugs that a more precise type would detect.
For example, accessing a nonexistent property or calling a value that is not actually a function can still produce a runtime error even when TypeScript reports no error for the operation. Use any sparingly and replace it with a more accurate type when possible.
2. Problems Caused by Excessive any Usage
Using any unnecessarily weakens type checking. Once a value is assigned to any, TypeScript cannot reliably protect that part of the code from incompatible assignments or unsafe operations.
function displayUsername(user: any): string {
return user.profile.name.toUpperCase();
}
console.log(
displayUsername({ username: "Asha" })
);
The function expects the supplied object to contain profile.name, but the caller provides a username property instead. Because the parameter is any, TypeScript does not report this mismatch at the function call. The property access can fail at runtime.
A better approach is to define the required structure when it is known:
interface User {
profile: {
name: string;
};
}
function displayUsername(user: User): string {
return user.profile.name.toUpperCase();
}
const user: User = {
profile: {
name: "Asha"
}
};
console.log(displayUsername(user));
The interface specifies the expected object structure. TypeScript can now detect missing properties and incompatible values in checked code.
3. Understanding the unknown Type
The unknown type can hold values of any type, but it does not allow unrestricted operations on those values. Before using a value in an operation that requires a specific type, you must first establish that the value supports that operation.
let value: unknown = "TypeScript";
value = 42;
value = true;
value = { course: "TypeScript" };
// Compile-time error:
// console.log(value.course);
Reassigning different types is allowed because unknown can represent values of any type. However, directly accessing value.course is not safe because the compiler cannot establish that value is an object containing that property.
You can safely use an unknown value after checking its type:
function displayValue(value: unknown): string {
if (typeof value === "string") {
return value.toUpperCase();
}
if (typeof value === "number") {
return value.toFixed(2);
}
if (typeof value === "boolean") {
return value ? "Yes" : "No";
}
return "Unsupported value";
}
console.log(displayValue("typescript"));
console.log(displayValue(42));
console.log(displayValue(true));
The typeof checks narrow the type of value inside each branch. TypeScript permits string operations in the string branch, numeric operations in the number branch, and Boolean-specific logic in the Boolean branch.
Unknown is particularly useful when receiving data from external sources because it encourages developers to verify a value before trusting its structure or performing operations on it.
4. any vs unknown
Both any and unknown can represent values of different types, but they differ in how TypeScript checks their usage. Any permits most operations without meaningful type verification, while unknown requires the value to be narrowed or checked before type-specific operations can be performed.
| Feature | any | unknown |
|---|---|---|
| Can hold different value types | Yes | Yes |
| Allows unchecked property access | Generally yes | No |
| Requires type narrowing before most type-specific operations | No | Yes |
| Useful for unvalidated input | Not recommended | Yes |
| Risk of hiding type errors | High | Lower, because checks are required |
let flexible: any = "hello";
// Allowed by TypeScript, but may fail at runtime.
// flexible.toFixed(2);
let safeValue: unknown = "hello";
// Compile-time error:
// safeValue.toUpperCase();
if (typeof safeValue === "string") {
console.log(safeValue.toUpperCase());
}
Prefer unknown when the actual type is not established. This is especially important when parsing JSON, reading browser storage, accepting values from loosely typed libraries, or handling data received from APIs. Use any only when bypassing type checks is a deliberate and justified choice.
5. Validating Unknown Objects
A typeof check is useful for primitive types, but an object may require additional validation of its properties. TypeScript supports user-defined type guard functions, which can verify an unknown value and indicate the type that has been established.
interface Product {
id: number;
name: string;
}
function isProduct(value: unknown): value is Product {
if (typeof value !== "object" || value === null) {
return false;
}
if (!("id" in value) || !("name" in value)) {
return false;
}
return (
typeof value.id === "number" &&
typeof value.name === "string"
);
}
function displayProduct(value: unknown): string {
if (!isProduct(value)) {
return "Invalid product";
}
return value.name.toUpperCase();
}
console.log(
displayProduct({ id: 101, name: "Keyboard" })
);
console.log(
displayProduct({ id: "wrong", name: "Keyboard" })
);
The isProduct function checks that the value is a non-null object with the required properties and expected primitive types. Its return type, value is Product, tells TypeScript that a true result establishes the Product type for subsequent checks.
This example validates the fields required by the Product interface. More complex models may require validation of nested objects, allowed values, numeric ranges, and additional business rules. For larger APIs, a runtime schema-validation library can help centralize those checks.
6. Using unknown with JSON Data
JSON parsing is a common place where developers encounter values that have not yet been validated. Data may come from an API, a local file, or browser storage, and its actual structure may not match the expected application model.
interface User {
id: number;
name: string;
}
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) {
return false;
}
if (!("id" in value) || !("name" in value)) {
return false;
}
return (
typeof value.id === "number" &&
typeof value.name === "string"
);
}
const data: unknown = JSON.parse(
'{"id":1,"name":"Asha"}'
);
if (isUser(data)) {
console.log(data.name);
} else {
console.error("Invalid user data");
}
The result of JSON.parse is assigned to unknown, so the code validates the data before using it as a User. The type guard confirms the required fields and their types.
JSON.parse can throw a SyntaxError when the input is malformed. Production code should also handle parsing errors when the JSON source is not guaranteed to be valid.
Declaring a value as User through a type assertion does not perform equivalent validation. Type annotations and assertions are compile-time constructs, while data validation must examine the actual runtime value.
7. Understanding the never Type
The never type represents values that cannot occur in a particular type context. It commonly appears as the return type of functions that never complete normally, such as functions that always throw an exception or remain in an infinite loop.
function fail(message: string): never {
throw new Error(message);
}
function runForever(): never {
while (true) {
// This function never completes normally.
}
}
fail("Unable to complete operation");
The fail function throws an error rather than returning a value. Similarly, runForever never reaches the end of its body because its loop continues indefinitely.
Never differs from void. A void function can finish execution without returning a meaningful result, whereas a never-returning function does not complete normally. This distinction helps TypeScript reason about unreachable code and exhaustive type handling.
8. Using never for Exhaustive Type Checking
One important use of never is detecting whether every possible case of a union type has been handled. This technique is known as exhaustive checking and is useful for status values, application states, and discriminated unions.
type RequestStatus =
| "loading"
| "success"
| "error";
function getStatusMessage(
status: RequestStatus
): string {
switch (status) {
case "loading":
return "Loading data";
case "success":
return "Request completed";
case "error":
return "Request failed";
default: {
const unexpected: never = status;
return unexpected;
}
}
}
console.log(getStatusMessage("success"));
After the three union members have been handled, TypeScript narrows status to never in the default branch. Assigning the value to a never variable checks that there are no remaining alternatives.
If a new status such as "cancelled" is added to RequestStatus without adding a corresponding case, the compiler reports an error at the exhaustive check. This makes it easier to discover incomplete logic when an application model changes.
Exhaustive checks are especially valuable in large applications because new states may affect several components and services. The never assignment helps identify each location that needs to be reviewed.
9. How never Appears in Type Narrowing
TypeScript removes possibilities from a union when conditions or switch statements narrow a value. If every possible alternative has been eliminated, the remaining type is never because no valid value remains in that context.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rectangle"; width: number; height: number };
function getArea(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius * shape.radius;
case "rectangle":
return shape.width * shape.height;
default: {
const unexpectedShape: never = shape;
return unexpectedShape;
}
}
}
console.log(getArea({ kind: "circle", radius: 5 }));
console.log(
getArea({
kind: "rectangle",
width: 10,
height: 4
})
);
The Shape type is a discriminated union whose alternatives are identified by the kind property. The switch statement handles both valid shapes and allows TypeScript to narrow shape to never in the default branch.
If another shape is added later, such as a triangle, the exhaustive check will identify that the function needs to be updated. This helps ensure that calculations and other behavior remain consistent as a model grows.
10. Understanding the Difference Between void and never
The void and never types can both appear as function return annotations, but they represent different behaviors. Void indicates that the function does not provide a meaningful result to its caller. Never indicates that it does not complete normally by returning or reaching the end of the function.
| Feature | void | never |
|---|---|---|
| Purpose | No meaningful return result | No normal completion |
| Can finish execution normally | Yes | No |
| Common example | Logging or notifications | Always-throwing function |
| Common additional use | Callbacks whose result is ignored | Exhaustive type checking |
function logMessage(message: string): void {
console.log(message);
}
function throwError(message: string): never {
throw new Error(message);
}
logMessage("This operation can complete normally");
// throwError("This operation throws an error");
The logging function finishes normally after writing a message. The error function always throws an exception and does not return normally. Choosing the correct return type communicates the intended control flow to TypeScript and to other developers.
11. When Should You Use any, unknown, and never?
Use any cautiously
Any can help during a gradual migration from JavaScript or when interacting with code that has no usable type declarations. Isolate its use and replace it with a more precise contract whenever possible.
Use unknown for uncertain inputs
Unknown is well suited to API data, parsed JSON, external values, and exception values whose actual type has not been verified. Narrow or validate the value before using its properties or methods.
Use never for impossible outcomes
Never is useful for functions that cannot complete normally and for exhaustive checks that ensure all known members of a union have been handled.
Choosing the appropriate type keeps the code's intent clear. Any trades type safety for flexibility, unknown retains flexibility while requiring verification, and never helps represent the absence of possible values in a particular type context.
12. Common Mistakes with any, unknown, and never
Using any to silence every compiler error
Any removes many useful checks. Prefer a specific interface, union type, or unknown with validation when the intended data structure can be described.
Treating unknown like any
Unknown values cannot be used freely with type-specific operations. Narrow the value with type checks, property checks, or an appropriate validation function first.
Confusing never with void
Void represents a function without a meaningful return result, whereas never represents a function that does not complete normally.
Assuming type guards validate every business rule
A type guard must actually check the properties required by its claimed type. Additional business rules and runtime constraints may require further validation.
Forgetting exhaustive checks
A switch statement may compile even when it omits an important case. Use never-based exhaustive checks for unions when every alternative must be handled.
Conclusion
The any, unknown, and never types serve distinct purposes in TypeScript. Any provides flexibility by disabling most checks, unknown represents unverified values that require narrowing, and never represents impossible values or operations that do not complete normally.
Prefer accurate types whenever possible, use unknown for external or uncertain data, and apply never to exhaustive checks and functions that cannot return normally. These practices help preserve the benefits of TypeScript's type system and make applications easier to debug, maintain, and extend.