Typesafe access of 'unknown' type

I'm trying to access the error variables returned by a try-catch
7 Replies
domi?
domi?OP4y ago
try {
// ...
} catch (e) {
if (e instanceof Object) {
console.log(e.message); // Property 'message' does not exist on type 'Object'
}
}
try {
// ...
} catch (e) {
if (e instanceof Object) {
console.log(e.message); // Property 'message' does not exist on type 'Object'
}
}
e is not an instance of Error as it's thrown by a third party library. How can I access the message key without casting to another type?
6enton
6enton4y ago
Since you don't know the type of an error you'll have to conditionally access it. Something like
try {
// ...
} catch (e) {
let message
if (e instanceof Error){
message = e.message
} else {
message = String(e) // or a custom message
}
console.log(message)
}
try {
// ...
} catch (e) {
let message
if (e instanceof Error){
message = e.message
} else {
message = String(e) // or a custom message
}
console.log(message)
}
I think Kent has an article about this lemme find it yep https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript
domi?
domi?OP4y ago
Thanks, that is a pretty good article. However, e is not an instance of Error as it's thrown by a third party library. It's just a normal object
ironnator
ironnator4y ago
Currently, I don't think there's a real nice way. You can hack around it by casting it to your own custom error object as you mentioned. But the type safe way to do it (for now) would be some sort of type guard function - found this thread which might help. https://stackoverflow.com/questions/70028907/narrowing-an-object-of-type-unknown
Unknown User
Unknown User4y ago
Message Not Public
Sign In & Join Server To View
6enton
6enton4y ago
that's really nice Do you know the type being thrown?
domi?
domi?OP4y ago
that's really nice It's just a normal object, no class

Did you find this page helpful?