字符串与字符串文字不兼容

1 javascript flowtype

我从这个代码片段中得到了流程错误

type MyType = 'aa' | 'bb'

const str = 'a'
const test1: MyType = `a${str}` // ERROR
const test2: MyType = 'a' + str // ERROR
Run Code Online (Sandbox Code Playgroud)

错误

const test1: MyType = `a${str}` // ERROR
                         ^ Cannot assign template string to `test1` because: Either string [1] is incompatible with string literal `aa` [2]. Or string [1] is incompatible with string literal `bb` [3].
References:
6: const test1: MyType = `a${str}`  // ERROR
                         ^ [1]
3: type MyType = 'aa' | 'bb'
                 ^ [2]
3: type MyType = 'aa' | 'bb'
                        ^ [3]
Run Code Online (Sandbox Code Playgroud)

链接:https : //flow.org/try

有谁知道为什么 flow 不支持这个?或者有没有更好的方法来编写这段代码来让流程开心?谢谢!

小智 5

Flow 是Javascript的静态类型检查器。这意味着 Flow 仅以静态方式分析源代码。

在您的示例中,test1test2变量aa运行时都将变为等于,这等于 的两个授权值之一MyType

不幸的是,这是一个运行时结果。Flow 只检查静态规则。据我所知,Flow 从不执行它检查的代码(即使代码像您的示例中那样微不足道)。