28

In C#, it is possible to invoke a given method with named arguments:

myObject.SetSize(width: 100, height: 100);

They primarily seem to exist for catering to optional parameters, but... They also drastically improve readability of method call sites. It also protects you from incorrect parameter specification.

From what I have been able to gather, if I wish to benefit from 'declarative call sites' in TypeScript I'm best off using 'argument objects' based on a given interface.

interface SizeArguments {
  width: number;
  height: number;
}

export class MyClass {

  setSize(args: SizeArguments) {
    /* Set size... */
  }
}

new MyClass().setSize({ width: 100, height: 100 });

Works for me! But that's still quite a lot of work for something so trivial in C#. Is this approach the best I can do right now? Or am I overseeing something fundamentally?

pizzaisdavid
  • 455
  • 3
  • 13
Rob Wijkstra
  • 801
  • 1
  • 7
  • 19
  • 2
    Have a look at https://github.com/Microsoft/TypeScript/issues/467 for the reasons to not add it to TypeScript. – str Mar 09 '17 at 11:01
  • 1
    See also: http://stackoverflow.com/questions/42108807/using-named-parameters-javascriptbased-on-typescript/42108988#42108988 – Paleo Mar 09 '17 at 13:17
  • 32
    Instead of going through the pain of creating "argument objects" for every function, just declare them inline: `setSize(args: { width: number, height: number })` – Ian Kemp Feb 22 '19 at 06:01
  • That looks cool @IanKemp; I'll have a look at that. – Rob Wijkstra Feb 26 '19 at 09:56
  • 2
    @IanKemp that's an excellent suggestion - you should post it as an answer ('no, but try this...'). – mikemaccana Apr 01 '20 at 16:11
  • in Ocaml its called "labeled" arguments. will TS ever get such a feature? –  Apr 19 '20 at 08:38

0 Answers0