Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

overloading - 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?

question from:https://stackoverflow.com/questions/39187614/typescript-overload-arrow-functions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...