Typescript overload arrow functions

给你一囗甜甜゛ 提交于 2020-01-22 13:48:05

问题


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?


回答1:


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. I could also declare it as number|object, but I prefer it like that. Its easier to extend with other overloads, shorter and as far as I know it doesnt actually block your type-checking as your overload signatures will do that.




回答2:


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.



来源:https://stackoverflow.com/questions/39187614/typescript-overload-arrow-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!