Properties declarations on functions

TypeScript 3.1 brings the ability to define properties on function declarations and const-declared functons, simply by assigning to properties on these functions in the same scope.This allows us to write canonical JavaScript code without resorting to namespace hacks.For example:

  1. function readImage(path: string, callback: (err: any, image: Image) => void) {
  2. // ...
  3. }
  4. readImage.sync = (path: string) => {
  5. const contents = fs.readFileSync(path);
  6. return decodeImageSync(contents);
  7. }

Here, we have a function readImage which reads an image in a non-blocking asynchronous way.In addition to readImage, we’ve provided a convenience function on readImage itself called readImage.sync.

While ECMAScript exports are often a better way of providing this functionality, this new support allows code written in this style to “just work” TypeScript.Additionaly, this approach for property declarations allows us to express common patterns like defaultProps and propTypes on React stateless function components (SFCs).

  1. export const FooComponent = ({ name }) => (
  2. <div>Hello! I am {name}</div>
  3. );
  4. FooComponent.defaultProps = {
  5. name: "(anonymous)",
  6. };

[1] More specifically, homomorphic mapped types like in the above form.