gpt4 book ai didi

javascript - 流类型: handling a function argument that could be many types

转载 作者:行者123 更新时间:2023-11-28 04:10:35 25 4
gpt4 key购买 nike

我不确定如何让流程来处理多种类型联合的参数。

示例代码:

// @flow

function foo(a: string | number[] | Date): string {
if (typeof a === 'string') {
return a.toUpperCase()
} else if (a instanceof Array) {
return a.join('-')
} else if (a instanceof Date) {
return a.getMonth().toString()
}
return ''
}

流程错误:

6:  } else if (a instanceof Array) {
^ Array. This type is incompatible with
3: function foo(a: string | number[] | Date): string {
^ union: string | array type | Date

Try flow link

当我使用 typeof 时,Flow 似乎确实注意到了,但这并不总是足够好,因为 typeof []typeof new Date() > 都是“对象”

如何让 Flow 在这里给我一个绿色的勾?

最佳答案

我刚刚尝试了您的示例并更改了 if 的顺序!

// @flow

function foo(a: string | number[] | Date): string {
if (typeof a === 'string') {
return a.toUpperCase()
} else if (a instanceof Date) {
return a.getMonth().toString()
} else if (a instanceof Array) {
return a.join('-')
}
return ''
}

没有报错。

别问我为什么:)

关于javascript - 流类型: handling a function argument that could be many types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46308131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com