打字稿重载箭头函数 [英] Typescript overload arrow functions

查看:36
本文介绍了打字稿重载箭头函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我们可以这样做:

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?

推荐答案

我猜它是在当时和现在之间添加的,因为您现在可以使用接口或类型来完成它(无关紧要,除了关键字之外的语法相同).当然也可以作为出口使用.该函数必须命名(我认为所有重载函数都必须命名),因此如果要将其用作回调,则必须先声明它.

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.

此外,作为任何与此相关的问题的前言,是的,我已在实现中将该参数声明为 any.在当前状态下,这是允许编译所必需的,是的,正如@ford04 指出的那样,您将失去函数内部的类型安全性.当涉及到函数及其返回时,似乎打字稿仍然无法正确处理标记的联合.或者,您可以使用更严格的参数,但您必须将返回值强制转换为 any.

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.

这篇关于打字稿重载箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆