作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我不确定如何让流程来处理多种类型联合的参数。
示例代码:
// @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
时,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/
我是一名优秀的程序员,十分优秀!