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:
In this TypeScript version:
We define a custom
ArgError
class that extends the built-inError
class. This is similar to implementing theerror
interface in Go.The
ArgError
class has a constructor that takes anarg
and amessage
. It also overrides thetoString
method to provide a custom string representation of the error.The
f
function throws anArgError
when the argument is 42, similar to returning a custom error in Go.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.Instead of
errors.As
, we use theinstanceof
operator to check if the caught error is an instance ofArgError
. This allows us to access the specific properties of our custom error.
To run this TypeScript program:
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.