How Should You Type catch Errors in TypeScript?

Learn How Should You Type catch Errors in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to unknown in TypeScript

The unknown type represents a value whose specific type is not yet known. It allows TypeScript to store a value without assuming that the value is a string, number, object, or another specific type.

This is especially useful when handling errors. JavaScript allows code to throw different kinds of values, including Error objects, strings, numbers, and ordinary objects. Therefore, a caught exception cannot always be assumed to have a message property or another familiar structure.

TypeScript uses unknown to encourage developers to inspect a value before using it. You can assign values to an unknown variable, but you must narrow its type or validate its structure before performing operations that require a more specific type.

Understanding unknown is important for reliable exception handling, parsing JSON, processing API responses, reading external data, and building applications that do not blindly trust values whose structure has not been verified.

1. Understanding the unknown Type

A variable declared as unknown can hold values of different types. TypeScript permits these assignments because the variable does not claim to have any particular structure.

let value: unknown;

value = "TypeScript";
value = 100;
value = true;
value = { name: "Abhinash" };
value = null;

console.log(value);

All the assignments above are valid. The important restriction appears when you attempt to use the value.

let value: unknown = "TypeScript";

// Compilation error:
// value.toUpperCase();

if (typeof value === "string") {
  console.log(value.toUpperCase());
}

TypeScript does not allow the direct method call because value might contain something other than a string. After the typeof check succeeds, the compiler narrows value to string within that block.

This behavior makes unknown useful at application boundaries, where a value may be valid but its structure has not yet been established.

2. Understanding unknown vs. any

Both unknown and any can hold values of different types, but they behave differently when you try to use those values. The distinction is important because any disables many type checks, whereas unknown requires the code to establish what operations are safe.

let unsafeValue: any = "TypeScript";

// Allowed by TypeScript, but assumes a method exists.
unsafeValue.toFixed(2);

let safeValue: unknown = "TypeScript";

// Compilation error:
// safeValue.toFixed(2);

if (typeof safeValue === "number") {
  console.log(safeValue.toFixed(2));
}

The any variable allows the invalid method call without a type error. If that operation executes on the string value, JavaScript throws a runtime error because strings do not provide the numeric toFixed method.

The unknown variable prevents the same unchecked operation. TypeScript requires a check before allowing the numeric method call.

Feature unknown any
Accepts values of different types Yes Yes
Allows unchecked property access No Yes
Requires narrowing before specific operations Yes Generally no
Useful for untrusted values Yes Usually less safe

Prefer unknown when the actual type is not yet known. Use any only when bypassing type checking is genuinely necessary and the consequences are understood.

3. Why Catch Variables Use unknown

JavaScript allows any value to be thrown. An exception might be an Error instance, a string, a number, or an object created by application code.

function performOperation(): void {
  throw "Operation failed";
}

try {
  performOperation();
} catch (error: unknown) {
  if (typeof error === "string") {
    console.error(error);
  } else if (error instanceof Error) {
    console.error(error.message);
  } else {
    console.error("An unexpected error occurred.");
  }
}

The thrown value in this example is a string rather than an Error object. Accessing error.message without checking the value would make an assumption that is not guaranteed by JavaScript.

TypeScript 4.4 introduced the useUnknownInCatchVariables compiler option. When strict mode is enabled, catch variables are treated as unknown by default unless the setting is overridden.

This encourages code to inspect the exception before accessing its properties. It also helps identify cases where a program assumes all failures follow the same structure.

As a general practice, prefer throwing Error instances for application failures. However, handling caught values as unknown remains a good defensive programming habit because third-party code may throw other kinds of values.

4. Narrowing unknown with instanceof

The instanceof operator checks whether a value is an instance of a particular class or constructor's prototype chain. It is commonly used to recognize standard Error objects and custom error classes.

function handleError(error: unknown): void {
  if (error instanceof Error) {
    console.error("Error name:", error.name);
    console.error("Error message:", error.message);
    return;
  }

  console.error("A non-Error value was thrown.");
}

try {
  throw new Error("Unable to save the user.");
} catch (error: unknown) {
  handleError(error);
}

When the instanceof condition succeeds, TypeScript narrows the value to Error. The code can then access properties such as name and message safely according to that type.

If the value is not an Error instance, the function follows the alternative branch without assuming that the value provides the same properties.

This approach works well for ordinary application exceptions and custom errors that extend Error. When dealing with values from different JavaScript environments or serialized error objects, additional validation may be necessary because instanceof depends on runtime constructor identity and prototype relationships.

5. Narrowing unknown with typeof

The typeof operator checks the runtime category of a value. It is helpful when a caught value might be a string, number, boolean, function, or another JavaScript value.

function describeError(error: unknown): string {
  if (typeof error === "string") {
    return "String error: " + error;
  }

  if (typeof error === "number") {
    return "Numeric error: " + error;
  }

  if (typeof error === "boolean") {
    return "Boolean error: " + error;
  }

  if (error instanceof Error) {
    return "Exception: " + error.message;
  }

  return "Unknown error type";
}

console.log(describeError("Request failed"));
console.log(describeError(500));
console.log(describeError(new Error("Database unavailable")));

Each condition narrows the value to a more specific type. The code can then use the value in a way that matches its actual runtime category.

Remember that typeof has specific JavaScript behavior. For example, typeof null returns "object", and arrays also return "object". When checking for objects, functions, arrays, or null, use the appropriate additional conditions rather than relying on typeof alone.

6. Safely Extracting Error Messages

Applications often need a consistent way to obtain a readable message from an unknown exception. A reusable helper can handle common cases without assuming that every thrown value is an Error object.

function getErrorMessage(error: unknown): string {
  if (error instanceof Error) {
    return error.message;
  }

  if (typeof error === "string") {
    return error;
  }

  if (
    typeof error === "object" &&
    error !== null &&
    "message" in error &&
    typeof error.message === "string"
  ) {
    return error.message;
  }

  return "An unexpected error occurred.";
}

console.log(getErrorMessage(new Error("Save failed")));
console.log(getErrorMessage("Network unavailable"));
console.log(getErrorMessage({ message: "Invalid input" }));
console.log(getErrorMessage(500));

The function handles Error instances first, then string values, and finally objects that contain a string message property. If none of those checks succeeds, it returns a generic message.

The object check excludes null because JavaScript reports null as an object through typeof. The in operator checks whether the message property exists, and the typeof check verifies that the property contains a string.

This helper is useful for diagnostic logging and consistent error reporting. For user-facing messages, consider mapping internal errors to approved messages instead of displaying raw exception details that might expose implementation information.

7. Using Custom Type Guards with unknown

A custom type guard is a function that checks whether a value satisfies a specific type. Its return type uses a type predicate such as value is SomeType, allowing TypeScript to narrow the value when the function returns true.

type ErrorWithCode = {
  message: string;
  code: string;
};

function isErrorWithCode(
  value: unknown
): value is ErrorWithCode {
  return (
    typeof value === "object" &&
    value !== null &&
    "message" in value &&
    typeof value.message === "string" &&
    "code" in value &&
    typeof value.code === "string"
  );
}

function handleFailure(error: unknown): void {
  if (isErrorWithCode(error)) {
    console.error(error.code + ": " + error.message);
    return;
  }

  console.error("An unrecognized failure occurred.");
}

handleFailure({
  message: "Connection lost",
  code: "NETWORK_ERROR"
});

The isErrorWithCode function verifies the properties required by ErrorWithCode. When the check succeeds, TypeScript allows handleFailure to access both code and message.

This pattern is useful when an application uses structured error objects that do not necessarily extend Error, such as objects received from a service or produced by a particular library.

A type guard must perform checks that genuinely support the type predicate it declares. Merely asserting that a value has a type does not validate the object or make the claim true at runtime.

8. Creating Custom Error Classes

Custom error classes provide a structured way to represent application-specific failures. They can include additional information and let calling code distinguish known error categories with instanceof.

class UserNotFoundError extends Error {
  constructor(public readonly userId: number) {
    super("User not found: " + userId);
    this.name = "UserNotFoundError";
  }
}

class ValidationError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "ValidationError";
  }
}

function findUser(userId: number): string {
  if (userId !== 101) {
    throw new UserNotFoundError(userId);
  }

  return "Abhinash";
}

try {
  console.log(findUser(999));
} catch (error: unknown) {
  if (error instanceof UserNotFoundError) {
    console.error("Missing user ID:", error.userId);
  } else if (error instanceof ValidationError) {
    console.error("Validation failed:", error.message);
  } else if (error instanceof Error) {
    console.error(error.message);
  } else {
    console.error("An unexpected error occurred.");
  }
}

UserNotFoundError carries a user identifier, while ValidationError represents invalid input. The catch block checks each supported error category and responds according to the information available.

Custom errors are useful when callers need to distinguish domain-specific failures. They also make code easier to understand because the type of error communicates why the operation failed.

Keep error categories meaningful and manageable. A well-defined set of error classes is usually more useful than creating a separate class for every slightly different error message.

9. Using unknown for API Responses

Values received from external sources should not automatically be trusted to match a TypeScript interface. An API may return an unexpected structure, a missing property, or a value with an incorrect type.

Treat uncertain data as unknown and validate it before using it as a trusted model.

type User = {
  id: number;
  name: string;
};

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof value.id === "number" &&
    "name" in value &&
    typeof value.name === "string"
  );
}

function processUser(data: unknown): string {
  if (!isUser(data)) {
    throw new Error("Invalid user response.");
  }

  return data.name.toUpperCase();
}

const apiResponse: unknown = {
  id: 101,
  name: "Abhinash"
};

console.log(processUser(apiResponse));

The isUser function checks that the required properties exist and contain values of the correct types. After the check succeeds, the compiler narrows data to User.

The type annotation on apiResponse does not validate the object. It simply forces the example to treat the value as unknown until a check establishes its structure.

This is especially important when parsing JSON or calling external APIs. TypeScript types disappear during compilation, so runtime validation remains necessary whenever the application must verify incoming data.

10. Handling unknown in Asynchronous Errors

Asynchronous functions can fail because of network errors, rejected promises, invalid responses, or exceptions raised by application code. When these failures are caught, handling the value as unknown allows the code to inspect it safely.

function getErrorMessage(error: unknown): string {
  if (error instanceof Error) {
    return error.message;
  }

  if (typeof error === "string") {
    return error;
  }

  return "An unexpected error occurred.";
}

async function loadUser(): Promise {
  try {
    const response = await fetch("/api/user");

    if (!response.ok) {
      throw new Error("Request failed: " + response.status);
    }

    const data: unknown = await response.json();

    console.log("User response received:", data);
  } catch (error: unknown) {
    console.error(getErrorMessage(error));
  }
}

The function checks the HTTP response status because fetch does not ordinarily reject its promise for an HTTP response such as 404 or 500. It explicitly throws an Error when the response is not successful.

If fetch rejects, JSON parsing fails, or another operation inside the try block throws, the catch block receives the failure and passes it to getErrorMessage.

The response data is also assigned to unknown to make its uncertain structure explicit. Before accessing specific response properties, add a suitable runtime validation step.

Always ensure asynchronous failures are awaited or have rejection handlers attached. An unawaited promise may reject after execution has moved beyond the try block, so that rejection will not automatically be handled by the surrounding catch statement.

11. Understanding unknown and Type Assertions

A type assertion tells TypeScript to treat a value as a specified type for static checking. It does not perform runtime validation and should not be used as a substitute for checking an unknown value.

type User = {
  id: number;
  name: string;
};

const response: unknown = {
  id: 101,
  name: "Abhinash"
};

// This changes the compiler's view but does
// not validate the actual value.
const assertedUser = response as User;

// Prefer validating the value first.
function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof value.id === "number" &&
    "name" in value &&
    typeof value.name === "string"
  );
}

if (isUser(response)) {
  console.log(response.name);
}

The assertion in assertedUser does not check the object's properties. If response contained an invalid value, the assertion would not fix that value or prevent all resulting runtime errors.

The type guard checks the actual runtime structure and narrows the value when the check succeeds.

Use assertions only when a type guarantee exists outside what TypeScript can determine. When the value is truly untrusted, prefer validation, parsing, or a custom type guard.

12. Common Mistakes to Avoid

  • Accessing properties before narrowing: an unknown value cannot be treated as a specific object until an appropriate check establishes its structure.
  • Assuming every caught value is an Error: JavaScript permits throwing values of many types. Use instanceof, typeof, or a custom type guard before accessing specific properties.
  • Replacing unknown with any: any removes many checks that would otherwise identify unsafe operations. Keep unknown until the required guarantees have been established.
  • Relying only on type assertions: assertions influence compile-time checking but do not validate runtime objects.
  • Treating all failures identically: expected validation failures, missing records, and unexpected system errors may need different handling strategies.
  • Ignoring malformed API responses: an interface declaration does not guarantee that a server has returned the expected properties and values.
  • Exposing raw exception details: stack traces and internal messages may contain information that should not be shown directly to end users.
  • Writing inaccurate type guards: a custom type predicate should only return true after the required runtime checks have actually passed.

13. Best Practices for unknown

  • Use unknown instead of any when accepting values whose types have not yet been established.
  • Handle caught exceptions as unknown and narrow them before accessing message, name, or custom properties.
  • Prefer throwing Error instances instead of arbitrary primitive values in application code.
  • Create custom error classes when callers need to identify important failure categories.
  • Use custom type guards or schema validation to check uncertain object structures.
  • Validate external values before treating them as application models.
  • Keep expected failure outcomes distinct from exceptional failures when designing function return types.
  • Use safe, consistent error messages for users and retain appropriate diagnostic details in protected logs.
  • Handle rejected promises explicitly and ensure asynchronous operations are awaited where necessary.
  • Avoid unnecessary assertions and broad any usage that bypasses the checks TypeScript can provide.

Conclusion

The unknown type is a valuable TypeScript feature for handling values whose structure or type is not yet known. It allows code to store uncertain values without permitting unsafe operations before the type has been checked.

When handling errors, combine unknown with instanceof, typeof, property checks, custom type guards, and custom error classes. These techniques help distinguish known failures from unexpected values while keeping the code type-safe.

By using unknown at application boundaries, validating external data, and handling exceptions carefully, you can reduce unsafe assumptions and build TypeScript applications that are easier to debug and more reliable.

Code Examples

Understand the unknown Type

typescript
let value: unknown = "TypeScript";

// Compilation error:
// value.toUpperCase();

if (typeof value === "string") {
  console.log(value.toUpperCase());
}

value = 100;

if (typeof value === "number") {
  console.log(value.toFixed(2));
}
    

Safely Handle a Caught Error

typescript
try {
  throw new Error("Unable to save the user.");
} catch (error: unknown) {
  if (error instanceof Error) {
    console.error(error.message);
  } else if (typeof error === "string") {
    console.error(error);
  } else {
    console.error("Unexpected error");
  }
}
    

Extract a Safe Error Message

typescript
function getErrorMessage(error: unknown): string {
  if (error instanceof Error) {
    return error.message;
  }

  if (typeof error === "string") {
    return error;
  }

  if (
    typeof error === "object" &&
    error !== null &&
    "message" in error &&
    typeof error.message === "string"
  ) {
    return error.message;
  }

  return "An unexpected error occurred.";
}

console.log(getErrorMessage(new Error("Save failed")));
console.log(getErrorMessage("Network unavailable"));
console.log(getErrorMessage({ message: "Invalid input" }));
    

Create a Custom Type Guard

typescript
type ErrorWithCode = {
  message: string;
  code: string;
};

function isErrorWithCode(
  value: unknown
): value is ErrorWithCode {
  return (
    typeof value === "object" &&
    value !== null &&
    "message" in value &&
    typeof value.message === "string" &&
    "code" in value &&
    typeof value.code === "string"
  );
}

const error: unknown = {
  message: "Connection lost",
  code: "NETWORK_ERROR"
};

if (isErrorWithCode(error)) {
  console.log(error.code, error.message);
}
    

Handle Custom Error Classes

typescript
class UserNotFoundError extends Error {
  constructor(public readonly userId: number) {
    super("User not found: " + userId);
    this.name = "UserNotFoundError";
  }
}

function findUser(userId: number): string {
  if (userId !== 101) {
    throw new UserNotFoundError(userId);
  }

  return "Abhinash";
}

try {
  console.log(findUser(999));
} catch (error: unknown) {
  if (error instanceof UserNotFoundError) {
    console.error("Missing user:", error.userId);
  } else if (error instanceof Error) {
    console.error(error.message);
  }
}
    

Validate an Unknown Object

typescript
type User = {
  id: number;
  name: string;
};

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof value.id === "number" &&
    "name" in value &&
    typeof value.name === "string"
  );
}

const response: unknown = {
  id: 101,
  name: "Abhinash"
};

if (isUser(response)) {
  console.log(response.name.toUpperCase());
}
    

Pro Tip

Treat every caught exception as unknown. First check whether it is an Error instance, then handle strings or supported custom error structures where necessary. Use type guards to validate uncertain values, and avoid replacing unknown with any or relying on type assertions when runtime validation is required.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.