javascript - 使用泛型流类型值数组

标签 javascript typescript flowtype

下面的代码

type Value<T> = {|
  name: string,
  value: T,
|}

const myNumber: Value<number> = { name: 'number', value: 1 };
const myString: Value<string> = { name: 'string', value: 'foo' };

const arr: Array<Value> = [myNumber, myString];

我想遍历 Value 的数组对象并获得 name我所有对象的值,但出现此错误:

9: const arr: Array<Value> = [myNumber, myString];
                    ^ Cannot use `Value` [1] without 1 type argument.
References:
1: type Value<T> = {|
             ^ [1]

关于如何在不使用 Value<any> 的情况下解决此问题的任何想法?我正在使用 flow strict

心流乐园 link

最佳答案

更新 在最新版本(使用 0.98.0 测试)中,流程能够正确推断类型,因此不再需要显式注释。只需:

const arr = [myNumber, myString];

旧版本:

在流程中你可以使用Existential Type (*)

An existential type is used as a placeholder to tell Flow to infer the type

const arr: Array<*> = [myNumber, myString];

Playground

关于javascript - 使用泛型流类型值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53076390/

相关文章:

javascript - 在 Notepad++ 中查找和替换以跟踪 URL

javascript - Angular ui-router 中的 fromState 返回空对象

javascript - 具有可变列布局的响应式网格

javascript - 子 Node 上的 XPath 选择

javascript - 如何使用 Vue 类组件访问 VueJS 3 和 Typescript 中的 HTML 引用?

javascript - 时刻验证仅适用于 React Native 中的某些设备

typescript - 文字类型推断 - Typescript

javascript - Flowtype 属性 'msg' 缺失为 null 或未定义

javascript - ES6 模块 : How to automatically re-export all types in the current directory from index. js?

javascript - 流类型: handling a function argument that could be many types