0

I have code like below,myFunc requires callback which needed generic parameter.

It looks like I can pass function which not required any parameters and not getting any error notification, any idea why?

const myFunc = <T>(callback: (par: T) => void) => {
  const param = ('test' as any) as T;
  callback(param);
};

const callback = (par: number) => {
  console.log(par);
};

myFunc<string>(callback); // Not working as suspected - OK
myFunc<string>(() => {}); // Why I do not getting any error notification here?

1 Answer 1

2

This is clearly described in handbook. Comparing two functions:

let x = (a: number) => 0;
let y = (b: number, s: string) => 0;

y = x; // OK
x = y; // Error

You may be wondering why we allow ‘discarding’ parameters like in the example y = x. The reason for this assignment to be allowed is that ignoring extra function parameters is actually quite common in JavaScript. For example, Array#forEach provides three parameters to the callback function: the array element, its index, and the containing array. Nevertheless, it’s very useful to provide a callback that only uses the first parameter

See also relevant section of TypeScript FAQ: Why are functions with fewer parameters assignable to functions that take more parameters?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.