I get an error in the console.log
statement below:
try {
// ...
} catch(e) {
if (typeof e === "object" && e !== null && e.hasOwnProperty("data")) {
console.log(e.data);
}
}
when I try to access e.data
, I get the following TypeScript error:
Property 'data' does not exist on type 'object'.ts(2339)
I explicitly check if e
has a property of data
though right? So I'm not understanding why TypeScript is saying data
doesn't exist on e.
How can I tell TypeScript properly that e has a property of data?
I know I can cast the error as an any
type, but I don't think this is good practice and would like to refrain from using any
if possible. My work does not allow for casting any
anywhere in the codebase.
screenshots of my errors below:
You can use a predicate !
try {
// ...
} catch (e) {
if (hasData(e)) {
console.log(e.data);
}
}
function hasData(object: unknown): object is { data: unknown } {
return (typeof object === "object" && object?.hasOwnProperty("data")) ?? false
}
[Playground][2]