we can safety access to deeper level of object by doing
data?.user?.age
but can I do casting at the same line?
const ageInNumber = +data?.user?.age!
typescript doesn't throw error but I'm not sure it won't give me trouble.
The optional chaining operator (?.) returns undefined if its first operand is null or undefined.
Casting undefined to a number won't raise any exceptions, just silently returns NaN. If that's acceptable to you, then that part is OK.
However, the non-null assertion (!) is problematic. According to this GitHub issue, TS evaluates a?.b! as (a?.b)!, asserting the entire chain, not just the .b part. So:
If none of the parts may ever be nullish, then the ?.'s are superfluous, and you should replace them with regular property access (.) to increase clarity.
If any of the parts can be nullish, it will short-circuit with undefined, and the non-null assertion is violated. If that's the case, you should remove the assertion.
However, if the last part (i.e. the age property of data.user) can be null (not undefined), then the entire chain returns null, which casts to 0, therefore is indistinguishable from a real zero received in the data. To make it NaN too (or set a default value), you can use the nullish-coalescing operator (??):
const ageInNumber = +(data?.user?.age ?? NaN)