0

Some functional programming languages provide the ability to call your functions inline 'between' arguments. I do not know the correct terminology for this functionality (if I did, I could do a better search :D), but hopefully the following is clear..

Let's say I define an 'add' function:

const add = (a,b) => a+b;

For reasons that are outside the scope of this question (I'm not here for a debate on coding style, there is a legitimate use-case here, I promise), I would like to be able to call this function like so:

const result = 1 add 3;

For my obviously more complicated situation than the above, this syntactic sugar would be very tasty. Is it possible in typescript? And what is the correct terminology/name for the behaviour above allowed in some languages?

Triazic
  • 3
  • 1
  • 1
    No, you'd have to write your own parser, probably one that transpiles to JS – CertainPerformance Feb 08 '21 at 03:23
  • Not possible... the closest I can think of in actual TypeScript to simulate infix functions would look like `_(1)(add)(3)` as in [this code](https://tsplay.dev/nWPqzw). – jcalz Feb 08 '21 at 04:27

1 Answers1

0

The terminology for this is an 'infix function', and no, it's largely not possible in TS.

Typescript is a very thin layer over Javascript: with only a few exceptions, it only supports the syntax that Javascript supports as well as the type annotations.

And Javascript doesn't have infix functions, so Typescript doesn't either.


The only way it's remotely possible is with a TS transformer, which is essentially writing a custom transpiler plugin that transpiles code to normal Typescript syntax.

But those are fragile and not very well supported, so I wouldn't recommend it for a syntax sugar use-case like this, personally.

Retsam
  • 30,909
  • 11
  • 68
  • 90