Typescript overload arrow functions

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.

Leave a Comment