具有常量字符串和依赖类型的流类型

Abr*_*m P 18 javascript types dependent-type ecmascript-6 flowtype

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

export default const FOO = 'FOO'

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

import FOO from '../consts/Foo'

然后我有一个功能:

const example = (foo : string) : {| type: FOO, foo: string |} => {
  return {type: FOO, foo: foo}
}
Run Code Online (Sandbox Code Playgroud)

这不是类似于:

  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
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:

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

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

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

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

Pet*_*all 11

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

type FOO = "FOO"
Run Code Online (Sandbox Code Playgroud)

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

const example = (foo : string) : {| type: FOO, foo: string |} => {
  return {type: "FOO", foo: foo}
}
Run Code Online (Sandbox Code Playgroud)

如果您使用除了需要"FOO"a 的确切字符串文字之外的任何值FOO,那么它是编译错误.

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

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

const example = (foo : string) : {| type: FooType, foo: string |} => {
  return {type: FOO, foo: foo}
}
Run Code Online (Sandbox Code Playgroud)

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