Typesafe access of 'unknown' type

I'm trying to access the error variables returned by a try-catch
7 Replies
domi?
domi?2y 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?
benten
benten2y 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?2y 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
ironnator2y 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 User2y ago
Message Not Public
Sign In & Join Server To View
benten
benten2y ago
that's really nice Do you know the type being thrown?
domi?
domi?2y ago
that's really nice It's just a normal object, no class
Want results from more Discord servers?
Add your server