[refactored] distanceFrom to have a shorthand signature
ClosedPublic

Authored by appsforartists on Oct 8 2017, 11:39 PM.

Diff Detail

Repository
R13 material-motion/material-motion-js
Lint
Automatic diff as part of commit; lint not applicable.
Unit
Automatic diff as part of commit; unit tests not applicable.
appsforartists created this revision.Oct 8 2017, 11:39 PM
Restricted Application added a reviewer: O2: Material Motion. · View Herald TranscriptOct 8 2017, 11:39 PM
Restricted Application added a project: Material Motion. · View Herald Transcript
Restricted Application added a reviewer: O3: Material JavaScript platform reviewers. · View Herald Transcript
Restricted Application added a reviewer: Material Motion. · View Herald Transcript
Restricted Application completed building Restricted Buildable.Oct 8 2017, 11:42 PM
vietanh accepted this revision.Oct 11 2017, 12:13 AM
vietanh added a subscriber: vietanh.
vietanh added inline comments.
packages/core/src/operators/distanceFrom.ts
51

Is 49-51 the way to do overloading methods for distanceFrom?

This revision is now accepted and ready to land.Oct 11 2017, 12:13 AM
appsforartists added inline comments.Oct 11 2017, 5:42 PM
packages/core/src/operators/distanceFrom.ts
51

In TypeScript, this is how overloading works:

method(firstSignature: A): void;
method(secondSignature: B): void;

method(actualSignature: A & B) {
  // implementation
}

For the purposes of type checking, when this method is called, TypeScript will try the first signature (A), and if that fails, it will try the second (B). Those are the only two valid ways to call the method - it never tries actualSignature.

On the other hand, the implementation needs to be handle the shape of both signatures. So, actualSignature is typed A & B. This might be an impossible type: there may not be an actual type that fulfills both A and B; however, since only the overloads are checked when this method is called, that doesn't matter. A & B tells TypeScript that the argument has all the properties of A and all the properties of B, so when you try to use the argument as an A or as a B in the implementation, TypeScript understands.

I only recently learned how to overload in TypeScript myself. Here is the guide about it:

https://www.typescriptlang.org/docs/handbook/functions.html#overloads

And if you're still curious, I'm happy to introduce you to Peter Burns. He's one of our resident TypeScript experts.

This revision was automatically updated to reflect the committed changes.