Amir
Amir

Reputation: 4760

How do I resolve error "Does not exist on type never"?

I am trying to define a function that might, or might not exist, depending on the JSON passed to the parent function. I do not know the name of the function that will be passed, and I don't know what kind of parameters it will get. I just know it will be an array of arguments, and I will call the apply method on my function.

I've created my interfaces, and I think this should work, as I've placed any[] on my fnParams index. However, I keep getting this error APPLY DOES NOT EXIST ON TYPE NEVER

declare let window: any;

interface CallbackJSON {
    fnContext: string;
    fnName: string;
    fnParams: any[];
}

interface UpdateJSON {
  someKey: string;
  anotherKey: string;
  oneMoreKey: string;
  callBackFn: CallbackJSON;  
}

export default function updateFunc(e: JQueryEventObject){
  const json: UpdateJSON = $(e.target).data('json');  
  const {someKey, anotherKey, oneMoreKey, callBackFn} = json;
  let fnContext, fnName, fnParams, _callBackFn: false | any[] = false;

  //Setup callback function if it's valid
  if(typeof callBackFn === 'object') {
    fnContext = callBackFn.fnContext
    fnName = callBackFn.fnName
    fnParams = callBackFn.fnParams
    _callBackFn = (fnName ? (fnContext ? window[fnContext][fnName] : window[fnName]) : false);
  }

  /* run some code */

  /* Then run callback function if it is a function */
  const runCallbackFn = function runCallbackFn() {
    if(typeof _callBackFn === 'function') {
      // APPLY DOES NOT EXIST ON TYPE NEVER
      _callBackFn.apply(null, fnParams);
    }
  }();
}

Upvotes: 0

Views: 799

Answers (1)

bcherny
bcherny

Reputation: 3172

You're declaring _callBackFn's type as false | any[], so it's not callable.

Try updating it to _callBackFn: false | any[] | Function = false.

Upvotes: 1

Related Questions