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

标签 javascript flowtype

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

示例代码:

// @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/

相关文章:

javascript - 如何确保给定键和值的对象类型的类型安全?

javascript - 为什么长度为 1 的数组在 JavaScript 中表现得像标量?

javascript - 将 JavaScript 附加到链接的推荐方法是什么

reactjs - 在React组件Props中使用通用流类型并实例化通用组件>

javascript - 什么是 "types first"流架构?

javascript - 如何正确输入这个 `makeCancellable`函数并使Flowtype停止提示?

react-native - 如何将 TouchableOpacity Props 类型与其他字段结合起来

javascript - 如何有条件地循环以将标题行映射到数据行

javascript - 对象范围内的变量访问

javascript - javascript 中的 getElementsByClassName() 错误