TypeScript Question

Typescript overload arrow functions

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download