打字稿重载箭头功能 [英] Typescript overload arrow functions

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

问题描述

所以我们可以这样做:

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所指出的,您将在函数内部释放类型安全性.在功能及其返回方面,打字稿似乎仍然无法正确处理已标记的并集.另外,您可以使用更严格的参数,但随后必须将返回值强制转换为任意值.

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天全站免登陆