Skip to content

Add :: operator - as shortcut for Function.bind call #38467

@moccaplusplus

Description

@moccaplusplus

Suggestion

I suggest addition of :: operator.
With behavior similar to Java - e.g. method reference.

Of course, we have function references in TypeScript/JavaScript now.
And functions have bind method, which allows to bind its this to the original object if needed.

This would be just a "syntactic sugar" for convenience .
The resulting JavaScript should stay untouched.

// having object like below:

let someObj = {
  val: 1,
  increment(): number {
    return val++;
  }
};

// You use bind to make context-aware method reference:

const incrObjVal = someObj.increment.bind(someObj);

// this might be equivalent to:

const incrObjVal = someObj::increment;
--------------------------^

Use Cases

  1. Reduce number of bind calls (in fluent API this may have dozens of them line after line)
  2. Reduce number of lambdas created only to wrap class method to make sure this context is maintained.
  3. Prevent from writing some methods as lambdas and some as "methods".
class SomeClass<T> {

  someObj: SomeOtherClass;

  someMethod(array: Array<T>): void {

    array
      .filter(this.lambdaLikeMethod)
      .filter(this.normalMethod.bind(this));
      .map(this.someObj.someFancyMapper.bind(this.someObj))

      // could be replaced with 
      // .filter(this::normalMethod)
      // .map(this.someObj::someFancyMapper);

      // and of course there's no problem to use :: operator on lambda, too
      // .filter(this::lambdaLikeMethod)
      // just as you could call
      // .filter(this.lambdaLikeMethod.bind(this))
      // it's abslutely correct - although not needed overhead

  }

  normalMethod(arg: T): boolean {
    // ..
  }

  // yes you may write it like this and then no use of `bind` is needed
  // but this makes code messy.
  lambdaLikeMethod = (arg: T): boolean => {
    // ..
  }
}

Checklist

My suggestion meets these guidelines:

  • [YES ] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [YES] This wouldn't change the runtime behavior of existing JavaScript code
  • [YES] This could be implemented without emitting different JS based on the types of the expressions
  • [YES] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [I HOPE SO ;)] This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions