strictBindCallApply

TypeScript 3.2 introduces a new —strictBindCallApply compiler option (in the —strict family of options) with which the bind, call, and apply methods on function objects are strongly typed and strictly checked.

  1. function foo(a: number, b: string): string {
  2. return a + b;
  3. }
  4. let a = foo.apply(undefined, [10]); // error: too few argumnts
  5. let b = foo.apply(undefined, [10, 20]); // error: 2nd argument is a number
  6. let c = foo.apply(undefined, [10, "hello", 30]); // error: too many arguments
  7. let d = foo.apply(undefined, [10, "hello"]); // okay! returns a string

This is achieved by introducing two new types, CallableFunction and NewableFunction, in lib.d.ts. These types contain specialized generic method declarations for bind, call, and apply for regular functions and constructor functions, respectively. The declarations use generic rest parameters (see #24897) to capture and reflect parameter lists in a strongly typed manner. In —strictBindCallApply mode these declarations are used in place of the (very permissive) declarations provided by type Function.

Caveats

Since the stricter checks may uncover previously unreported errors, this is a breaking change in —strict mode.

Additionally, another caveat of this new functionality is that due to certain limitations, bind, call, and apply can’t yet fully model generic functions or functions that have overloads.When using these methods on a generic function, type parameters will be substituted with the empty object type ({}), and when used on a function with overloads, only the last overload will ever be modeled.