【问题标题】:flow types with constant strings, and dependent types具有常量字符串和依赖类型的流类型
【发布时间】:2017-06-30 22:11:53
【问题描述】:

假设我有以下常量字符串:

export default const FOO = 'FOO'

假设我将它导入到流注释文件中,如下所示:

import FOO from '../consts/Foo'

然后我有一个函数:

const example = (foo : string) : {| type: FOO, foo: string |} => {
  return {type: FOO, foo: foo}
}

这不会与以下内容进行类型检查:

  6: const example = (foo : string) : {| type: FOO, foo: string |}=> {
                                                         ^^^^^^^^^^^^^^ string. Ineligible value used in/as type annotation (did you forget 'typeof'?)
  6: const example = (foo : string) : {| type: FOO, foo: string |}=> {
                                                         ^^^^^^^^^^^^^^ FOO

所以我的问题是:

1) 是否可以在流类型中使用常量,如何重现这种行为?

2) 是否可以在流中做依赖类型?例如,我是否可以通过类型编码返回的字符串必须与传递给example 函数的字符串相同?

编辑:对第 2 部分的说明:是否有可能以某种方式表明传递给 example 函数的 foo 参数实际上与返回对象中 foo 键处的字符串相同?或者断言输入和输出具有相同的长度(例如移位密码函数)。或者说包含相同字符的排列? (随机播放)。

https://en.wikipedia.org/wiki/Dependent_type

【问题讨论】:

  • 如果您希望FOO 具有'FOO' 类型,那么您需要声明它,否则它只是一个字符串。对于对象,您可以像错误所说的那样执行type: typeof FOO。不过,我不太确定您在 2) 中要问什么。然后你会得到一个对象,它有两个属性相同的字符串值。

标签: javascript types ecmascript-6 flowtype dependent-type


【解决方案1】:

不要将FOO 声明为const,而是将其声明为只有一个分支的不相交联合:

type FOO = "FOO"

然后你的代码可以这样更新:

const example = (foo : string) : {| type: FOO, foo: string |} => {
  return {type: "FOO", foo: foo}
}

如果您在需要 FOO 的确切字符串文字 "FOO" 之外使用任何值,则这是编译错误。

如果您希望保持不变,那么您需要以不同的方式命名类型,因为它们会发生冲突。所以你可以这样做:

const FOO = "FOO"
type FooType = "FOO";

const example = (foo : string) : {| type: FooType, foo: string |} => {
  return {type: FOO, foo: foo}
}

不幸的是,我看不到避免重复字符串文字的方法,因为类型不相交的联合定义语法只允许文字和类型,而不是变量,即使它们是常量。

【讨论】:

  • 对于将动作类型定义为字符串以清除代码中的一些引号的 Flux 标准动作模式,这是一个非常有趣的模式。这样,如果我错了,请纠正我,我可以定义一个元类型 ValidResponses = FOO | BAR ; 并确保 API 函数调用返回正确的响应,而不仅仅是正确的数据类型。
【解决方案2】:

找到了解决该问题的方法, 我们可以指定字面量类型,而不是使用流类型推断

export default const FOO:'FOO' = 'FOO'

然后在函数中你可以使用 as

const example = (foo : string) : {| type: typeof FOO, foo: string |} => {
return {type: FOO, foo: foo}
}

因为当你声明常量类型被推断为字符串时,我相信流不支持从变量或常量设置类型定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2020-01-07
    • 1970-01-01
    相关资源
    最近更新 更多