流量类型:处理函数的参数,可能是多种类型
问题描述:
我不知道如何让流程来处理许多类型的联合参数。流量类型:处理函数的参数,可能是多种类型
示例代码:
// @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
流量似乎当我使用typeof
,但事实并非总是不够好,因为typeof []
和typeof new Date()
注意都是"object"
。
如何使流量在这里给我一个绿色的检查?
答
我只是尝试用你的榜样和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 ''
}
没有错误。
不要问我为什么:)
+0
那么这有点神秘...... –
+0
你应该记录一个错误。 –
是否看起来像一个bug,但FYI它正常工作与'Array.isArray',你基本上总是要使用,而不是'的instanceof Array'。 – loganfsmyth
因为你定义了默认情况''return'',所以你对'foo'的类型安全性似乎并不特别自信。 – ftor
@ftor流似乎并没有意识到这些都是三个选项要么,所以没有这种gauranteed'回报“”'你'字符串:这种类型是不符合的隐式返回undefined.' –