90

So we can do:

export function myMethod (param: number) :number
export function myMethod (param: string) :string

export function myMethod (param: string | number): string | number {
  if (typeof param === 'string') {
    return param.toUpperCase()
  } else {
    return param + 1
  }
}

Can I declare and implement it with arrow function?

export var myMethodArror = (param: string): string
export var myMethodArror = (param: number): number

export var myMethodArror = (param: string | number): string | number => {
..
}

I am aware of that it is not possible to duplicate the variables declaration, but my question is: is it possible to make function overload using arrow notation?

Claudio Cortese
  • 1,372
  • 2
  • 10
  • 21
WHITECOLOR
  • 24,996
  • 37
  • 121
  • 181
  • 4
    Well of course it won't work. A variable cannot be declared twice, and a variable declaration does not declare a function signature. This is not an issue with arrow functions; the same would apply if you tried to do `export var myMethodArr = function(...)`. –  Aug 28 '16 at 04:58
  • 5
    But my question is it possible to make an overload using arrow notation – WHITECOLOR Aug 28 '16 at 05:14
  • Thanks, you could not comment but answer and get the bonus from havens) – WHITECOLOR Aug 28 '16 at 05:32
  • Duplicate of https://stackoverflow.com/questions/20646171/can-i-use-typescript-overloads-when-using-fat-arrow-syntax-for-class-methods#comment74062493_20646788 – Shachar Har-Shuv May 13 '19 at 09:25

4 Answers4

149

I guess it was added inbetween then and now, because you can do it now using an interface or type (doesnt matter, same syntax except the keyword). Also works as export of course. The function has to be named though (i think all overloaded functions have to), so you'll have to declare it first if you want to use it as callback.

type IOverload = {
    (param: number): number[];
    (param: object): object[];
}

const overloadedArrowFunc: IOverload = (param: any) => {
    return [param, param];
}

let val = overloadedArrowFunc(4);

I far prefer it like that, it reduces the need for duplicate writing. Writing the name again and again is annoying.

Also, to preface any questions regarding that, yeah I've declared the parameter as any in the implementation. This is neccessary at the current state to allow compilation, and yeah, you will loose type-safety inside the function, as @ford04 pointed out. It seems typescript still cant process flagged unions correctly when it comes to functions and their returns. Alternatively you can have stricter parameters but then you will have to cast the return to any.

Sejin Jeon
  • 338
  • 2
  • 4
  • 17
Sam96
  • 1,712
  • 1
  • 9
  • 15
  • 7
    this is an actual answer. I don't agree that writing the name over again is annoying but this explains how to overload the signature of an arrow function – Aluan Haddad Nov 04 '18 at 17:42
  • 4
    Disadvantage of this solution is that return types cannot be typed checked in the function body. See [here](https://www.typescriptlang.org/play/#code/C4TwDgpgBAkg8gNwgJwDYHsCGATKBeKAbwFgAoKCqACjE2UwFsAuKAOwFcGAjFAShY7cUAbQC6AbjKVqtesyjouAKwgBjYPyhd06VBEysxk0gF8yAenNRQkKKoAWagNYBLVgHMFAMyjIIwdmRWa3AIAGcoNzCXbGgvdlZ1F3Rg7WwQSIjWdGAoMHQw6K49agMMg2zgTGAIbF4LKwBBVFRff0Dgm3CoOmg3GuQwtRrsABo2sPZUYDdPNzZOHmQxKAAyLR09AzFxgHd7FwcoCC8vYZckVAyXLIgkZAA6MlUUsNz0e4wcWsbkZHRdgAxBKqFjwT5YXAEGh0RgsMqaMrmABUUAEixEojWG10+kMWORVjwAD4iFJKH4AkEoMIAEzjADMojIZlIelyCEwrQIHxQX1i2F+-yBIKoABZeOIgA) – ford04 Jan 13 '20 at 18:06
  • 2
    This is really great. However when I test out my type-checking, the error I get when matching the wrong 2nd parameter with my first parameter ( `type overload = { (first: type1a, second: type 1b): any, (first: type2a, second: type2b)` is `The last overload gave the following error: Argument of type 'type1a' is not assignable to parameter of type 'type1b'.` Which is confusing, it should be some like `type1a can't go with type2b`. Is there a way to fix that? – Jonathan Tuzman Jan 14 '20 at 19:40
  • 6
    `` is only admitting defeat if it's been less than an hour and a half right? That same constraint seems to still apply for what I'm doing. – Simon_Weaver Jun 27 '20 at 01:24
  • 2
    I like this...but how do I invoke a generic in IOverload? I'd like to use a generic to overload for different types. I'm trying different thing but unable to get the syntax right. – tslater Feb 25 '21 at 03:00
  • @tslater Hmm I dont have any more experience with that than you. I can imagine that thats not a thing to simplify the parser - and also our understanding. What should work however is generics on the type itself. Either as one parameter with an Union or as two seperate parameters (you can set defaults). – Sam96 Mar 15 '21 at 17:56
  • @ford04 is there any better way, without the disadvantage that you mention? – Qtax Sep 20 '21 at 18:04
  • @tslater Does wcandilon's answer suffice for your need to use a generic? https://stackoverflow.com/a/61379058/1736092 – spex Oct 15 '21 at 14:58
19

This solution is based on @Sam96 but keeps the code of the arrow function fully typed.

type Create = {
  (): Vector<0>;
  <T>(x: T): Vector<T>;
  <T>(x: T, y: T): Vector<T>;
};

const create: Create = <T>(
  x?: T,
  y?: T
) => ({
  x: x ?? 0,
  y: y ?? x ?? 0,
});
wcandillon
  • 2,086
  • 19
  • 19
  • 6
    This looks pretty cool. Could you extend on this answer and explain how it would work when all three parameters have different generic types that require your T as type argument? – wedi Jan 20 '21 at 04:27
8

You can use intersection operator & for overloading.

export let myMethodArror = ((param: string | number): string | number => {
...
}) as ((param: string) => string) & ((param: number) => number)
rot18
  • 81
  • 1
  • 2
4

The declaration of overloaded signatures is always

function name(args...): result;

with a function keyword and a function name.

Your syntax

var myMethodArror = (param: string): string;

is invalid. It is trying to assign something that looks like the beginning of an arrow function to a variable, but the function has no body. You will get the error

'=>' expected

If you repeat this with a a different signature, then you'll also get a duplicate property error, or perhaps the error

Subsequent variable declarations must have the same type.

This is not specific to arrow functions. The same problem would arise if you tried to do

var myMethodArror = function(param: string): string;

which would yield

'{' expected

since the function body is missing.