首页 > 解决方案 > 在类型参数上流 $ObjMap

问题描述

Flow 没有产生我在下面预期的错误。它是 Flow 的错误(可能)还是我误解了关于类型参数的一些东西?

function test<A: Object>(
  obj: A,
  mapper: $ObjMap<A, <V>(V) => V => any>
) {
}

test(
  {
    foo: 1,
    bar: '2',
  },
  {
    foo: (x: number) => String(x),
    bar: (x: number) => parseInt(x),
    //       ^^^^^^
    // should error that this is the wrong argument type
  }
)

这似乎是一个错误,因为以下内容会产生错误,尽管出现在错误的位置:

const a = {foo: 1, bar: '2'}
type A = typeof a
type B = $ObjMap<A, <V>(V) => V => any>

const b: B = {
  foo: x => String(x),
  bar: (x: number) => parseInt(x),
}

错误:

3: type B = $ObjMap<A, <V>(V) => V => any>
            ^ Cannot instantiate `$ObjMap` because string [1] is incompatible with number [2] in the first argument.
   References:
   1: const a = {foo: 1, bar: '2'}
                              ^ [1]
   7:   bar: (x: number) => parseInt(x),
                 ^ [2]

标签: flowtype

解决方案


好的,我能够使用它

declare function test<A: Object, M: $ReadOnly<$ObjMap<A, <I, O>(I) => I => O>>>(
  obj: A,
  mapper: M
): $ObjMap<M, <I, O>((I) => O) => O>

不理想,因为输出只能分配给一个$ReadOnly形状,但它涵盖了我需要的所有类型检查。


推荐阅读