tl;dr why does
const func = (a: unknown) => {
if (a && typeof a === 'object' && 'b' in a) {
a.b;
}
};
Give the following error message
Property 'b' does not exist on type 'object'.
?
Edit: After looking into this more closely I have an even more minimal example. So let me rephrase my question:
How to probably narrow object type in TypeScript?
tl;dr why does
const func = (a: object) => {
if ('b' in a) {
a.b;
}
give the following error message:
Property 'b' does not exist on type 'object'.
?
You should have a closer look at custom type guard. They basically let the compiler know, that if the condition passes, the checked value will have a specific type.
In your case:
const hasB = (value: unknown): value is { b: unknown } => {
return (
typeof value === 'object'
&& value !== null
&& 'b' in value
);
}
const func = (a: unknown) => {
if (hasB(a)) {
a.b;
}
};
Playgound example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With