Ole
Ole•7mo ago

Ensure error is of type unknown with Deno lint

I'm having an interesting issue in a catch (error) { block. The issue is resolved when I change it to error: unknown, as I then get a type error in the function I call later. When the error is any, I get no warning, and I'm quite sure I'll forget to manually add : unknown to all my errors, so I'm looking for a way to guard for this 🤔
2 Replies
Ole
OleOP•7mo ago
I'd love a deno_lint rule to enforce that I add : unknown to all my errors !! the useUnknownInCatchVariables rule seems to be my solution!
Deno AI Helper
Deno AI Helper•7mo ago
I wasn't able to find the answer to your question in the official Deno documentation. However, based on your message, it seems like you are looking for a way to enforce that caught errors are of type unknown by default, to ensure you handle them properly in TypeScript. In TypeScript, when you use a catch block, the error is implicitly of type any. To enforce that errors are of type unknown, you can use a TypeScript compiler option or a lint rule. However, as of my knowledge cutoff date, Deno's built-in linter does not have a specific rule that enforces caught errors to be of type unknown. As a workaround, you can manually specify the type of the caught error as unknown like this:
try {
// some code that might throw
} catch (error: unknown) {
// handle the error
}
try {
// some code that might throw
} catch (error: unknown) {
// handle the error
}
This will force you to perform type checks or type assertions before you can use the error object, which is a safer approach. Please note that this advice is not based on the Deno documentation, and I would advise you to double-check the accuracy of the advice given. It's also a good idea to keep an eye on updates to Deno and its linter, as new rules and features are added over time that might address this issue directly.

Did you find this page helpful?