From Mozilla:
The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
In your case, obj
is the reference being checked for null
or undefined
, not prop
.
So why does TS doesn't let me write this
You've told TS to expect an object
, but you have not told TS anything about the properties of that object, so it has no idea if prop
exists. In other words, prop
is not on the interface of object
, so it throws a compiler error.
is there a setting in my tsconfig.json I can set so that I can write that?
The behavior from above is the whole point of TypeScript, a static type checker. You do not want this exact behavior to be enabled, but there is an intended way within the language to produce the same effect:
const fn2 = (obj: Record<string, any>) => obj.prop;
The above code requires that obj
be non-null/undefined and allows for any string
(or number
, but not Symbol
) property accessor.
Playground