Weak Type Detection

TypeScript 2.4 introduces the concept of “weak types”.Any type that contains nothing but a set of all-optional properties is considered to be weak.For example, this Options type is a weak type:

  1. interface Options {
  2. data?: string;
  3. timeout?: number;
  4. maxRetries?: number;
  5. }

In TypeScript 2.4, it’s now an error to assign anything to a weak type when there’s no overlap in properties.For example:

  1. function sendMessage(options: Options) {
  2. // ...
  3. }
  4. const opts = {
  5. payload: "hello world!",
  6. retryOnFail: true,
  7. }
  8. // Error!
  9. sendMessage(opts);
  10. // No overlap between the type of 'opts' and 'Options' itself.
  11. // Maybe we meant to use 'data'/'maxRetries' instead of 'payload'/'retryOnFail'.

You can think of this as TypeScript “toughening up” the weak guarantees of these types to catch what would otherwise be silent bugs.

Since this is a breaking change, you may need to know about the workarounds which are the same as those for strict object literal checks:

  • Declare the properties if they really do exist.
  • Add an index signature to the weak type (i.e. [propName: string]: {}).
  • Use a type assertion (i.e. opts as Options).