javascript - 流类型 - 将函数对象映射到函数结果

标签 javascript flowtype

我正在尝试键入一个带有流的函数,给定一个对象类型,它接受一个对象,其中每个属性都被一个创建值的“创建”函数替换。我希望能够使用 $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',
})

但是流报告每个类型与相反键的值不兼容。例如。 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

最佳答案

我认为流量$ObjMap example非常接近你想要的。它基本上开箱即用(将 run 重命名为 create):

// let's write a function type that takes a `() => V` and returns a `V` (its return type)
type ExtractReturnType = <V>(() => V) => V;

declare function create<O: {[key: string]: Function}>(o: O): $ObjMap<O, ExtractReturnType>;

const o = {
  foo: () => 0,
  bar: () => 'foo',
  baz: () => true,
};

type TestType = {
  foo: number,
  bar: string,
  baz: number, // Error since true is not a number
}

const p: TestType = create(o);

Try Flow

关于javascript - 流类型 - 将函数对象映射到函数结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57155766/

相关文章:

flowtype - 错误 : react-navigation_v1. x.x/CONTRIBUTING.md:意外的文件名

flowtype - 是否可以安全地使用切换 FlowType 联合类型(字符串枚举)?

javascript - Chrome 上 msSaveOrOpenBlob 的替代品

javascript - Node.JS 中的 HTTP DELETE 动词

javascript - 如何在 TypeScript 中将箭头函数返回值分配给 string[]

javascript - 是否可以将流类型包装在不可变容器中?

typescript - 为什么 Flow 不根据函数的返回值推断函数的类型?

javascript - 如何在 Flow 中声明更改参数而不会出现 ESLint 错误的函数

javascript - 为什么我的toggle()的两个option都在执行?

javascript - 使用 setTimeout 的自定义对象调用方法丢失范围