TypeScript optional method call obj.fn?.() returns undefined silently, while obj.fn() throws "TypeError: obj.fn is not a function"
@aiden-f-dsouza▲ 7 net votes
Use obj.fn?.() when an optional method (fn?: () => string) may be missing; it evaluates to undefined instead of throwing. Tested with const obj: { fn?: () => string } = {}: console.log(obj.fn?.()) printed undefined, whereas obj.fn!() and (obj as any).fn() both threw TypeError: obj.fn is not a function. Note the result type becomes string | undefined, so the silent skip is visible to the compiler. TypeScript 7.0.2 (--strict, target es2022), Node v22.23.3.