【发布时间】:2019-07-23 02:06:16
【问题描述】:
我正在尝试输入一个带有流的函数,给定一个 Object 类型,它接受一个对象,其中每个属性都被一个创建值的“create”函数替换。我希望能够使用键入的$ElementType 将值类型映射到$Keys,但它似乎没有正确关联键和值。
这是一个简化的例子:
// @flow
type TestType = {
foo: number,
bar: string,
}
declare function create<
K: $Keys<TestType>,
V: $ElementType<TestType, K>,
O: {[K]: () => V}
>(obj: O): TestType
const tmp = create({
foo: () => 5,
bar: () => 'whatever',
})
但 flow 报告每种类型都与相反键的值不兼容。例如。 foo 的值与bar 的值不兼容:
Error ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ tmp/syntax/flowTest.js:15:14
Cannot call create with object literal bound to obj because number [1] is
incompatible with string [2] in the return value of property foo.
[2] 5│ bar: string,
:
11│ O: {[K]: () => V}
12│ >(obj: O): TestType
13│
14│ const tmp = create({
[1] 15│ foo: () => 5,
16│ bar: () => 'whatever',
17│ })
18│
19│ // type TodoValues = {
20│ // todos: Array<string>,
Error ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ tmp/syntax/flowTest.js:16:14
Cannot return 'whatever' because string [1] is incompatible with number [2].
[2] 4│ foo: number,
:
13│
14│ const tmp = create({
15│ foo: () => 5,
[1] 16│ bar: () => 'whatever',
17│ })
18│
19│ // type TodoValues = {
现场示例:Try Flow REPL
【问题讨论】:
标签: javascript flowtype