Custom Errors in TypeScript

Custom errors can be implemented in TypeScript by extending the built-in Error class. Here’s an example that demonstrates this concept:

import { format } from 'util';

// A custom error type usually has the suffix "Error".
class ArgError extends Error {
    constructor(public arg: number, message: string) {
        super(message);
        this.name = 'ArgError';
    }

    toString(): string {
        return format('%d - %s', this.arg, this.message);
    }
}

function f(arg: number): number {
    if (arg === 42) {
        // Return our custom error.
        throw new ArgError(arg, "can't work with it");
    }
    return arg + 3;
}

function main() {
    try {
        f(42);
    } catch (err) {
        // TypeScript doesn't have a direct equivalent to Go's errors.As,
        // but we can use instanceof to check the error type.
        if (err instanceof ArgError) {
            console.log(err.arg);
            console.log(err.message);
        } else {
            console.log("err doesn't match ArgError");
        }
    }
}

main();

In this TypeScript version:

  1. We define a custom ArgError class that extends the built-in Error class. This is similar to implementing the error interface in Go.

  2. The ArgError class has a constructor that takes an arg and a message. It also overrides the toString method to provide a custom string representation of the error.

  3. The f function throws an ArgError when the argument is 42, similar to returning a custom error in Go.

  4. In the main function, we use a try-catch block to handle the error. This is different from Go’s approach of returning errors, but it’s the idiomatic way to handle errors in TypeScript.

  5. Instead of errors.As, we use the instanceof operator to check if the caught error is an instance of ArgError. This allows us to access the specific properties of our custom error.

To run this TypeScript program:

$ ts-node custom-errors.ts
42
can't work with it

Note that you’ll need to have TypeScript and ts-node installed to run this directly. Alternatively, you can compile it to JavaScript and run it with Node.js.

This example demonstrates how to create and use custom errors in TypeScript, providing similar functionality to Go’s custom errors.