Search code examples
typescripttslint

tslint / typescript: Prevent function nesting


Is there a way to use tslint to prevent function nesting?

export const function DontBeLateDate =
  (isDifferent: boolean) =>
    (additionalMilliseconds: Number) =>
      new Date((isDifferent ? 13378335 : 83351337) + additionalMilliseconds);

resulting in:

DontBeLateDate(true)(1024);

Issue being isDifferent is is used within a nested function.

This should be valid:

export const function DontBeLateDate =
  (isSomethingElse: boolean) => {
    if (isSomethingElse) {
      return (isDifferent: boolean, additionalMilliseconds: Number) =>
              new Date((isDifferent ? 5 : 7) +
              additionalMilliseconds);
    }
    return (isDifferent: boolean, additionalMilliseconds: Number) =>
      new Date((isDifferent ? 13378335 : 83351337) +
          additionalMilliseconds);
  }

isSomethingElse scope does not bleed into the inner function.


Solution

  • There are two issues here: the first one is currying, i.e. having a function which returns a function, so that it can be called like f(x)(y). The second issue is creating a closure, i.e. the outer function has local variables which remain accessible by the inner function even after the outer function has returned.

    In the comments you've said closures are what you'd like tslint to warn about. This can be achieved using a third-party tslint rule named tslint-no-closures, which is available on GitHub. However, be aware that the README for this project currently says it is a work in progress.