1
votes

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)
}

here

1
Could you include all the code required to reproduce it? Preferably a TypeScript Playground. - Karol Majewski
@VLAZ I added full code, typescript 3.8.3 - Bobby
@KarolMajewski also notify you. - Bobby
OK, I see the problem, then. options?.event?.[name] === 'function' is used once but TS doesn't know that options.event[name] will fetch the same element. - VLAZ

1 Answers

0
votes

You can leverage optional chaining:

let dispatcher = function (name: TableEventName, params: any): any {
  const handler = options.event?.[name];

  return handler?.(params);
}