I have this code snippet.
interface OBJ {
a: {
b?: {
c?: number;
};
};
}
const obj: OBJ = {
a: {
b: {
c: 1
}
}
};
if (obj.a.b.c === 1) {
console.log("here");
}
Firstly the TS compiler complains about Object is possibly 'undefined'.ts(2532)
at obj
. I don't get it since it looks to me like the object is indeed defined, it is just according to the interface the b
and c
property can be undefined.
then I thought I could use optional chaining on it
if (obj.a.b?.c === 1) {
console.log("here");
}
However this time the compiler says there is a syntax error
/src/index.ts: Unexpected token (9:14)
7 | }
8 | };
> 9 | if (obj.a.b ? .c === 1 : ) {
| ^
10 | console.log("here");
11 | }
12 | //#
What am I missing here? Can someone please explain these two questions to me?
live demo: https://codesandbox.io/s/wizardly-booth-idpy5?file=/src/index.ts
Object is possibly 'undefined'.ts
because you're accessing it through theOBJ
interface, the actual value doesn't matter. And the second one is complaining about the whitespace - you've mixed up a ternary operator into your code for some reason, it's not optional chaining.b
andc
are optional.