I have the following code
dispatchEvent(name: TableEventName, params: any): any {
const event =
typeof this.options?.event?.[name] === 'function' ? this.options.event[name] : () => {}
return event(params)
}
which at compilation return
Cannot invoke an object which is possibly 'undefined'. return event(params)
I am doing the correct checking tho, why so ?
full code :
type TableEventName = 'onStateChange' | 'onSort' | 'onPageChange' | 'onSelection'
interface TableOptions {
event?: {
onStateChange?: (event: any) => void
onSort?: (event: any) => void
onPageChange?: (event: any) => void
onSelection?: (event: any) => void
}
}
let options: TableOptions = {
event: {
onSort: () => { }
}
}
let dispatcher = function (name: TableEventName, params: any): any {
const event =
typeof options?.event?.[name] === 'function' ? options.event[name] : () => {}
return event(params)
}
options?.event?.[name] === 'function'is used once but TS doesn't know thatoptions.event[name]will fetch the same element. - VLAZ