【问题标题】:Import flowtype disjoint union?导入流类型不相交的联合?
【发布时间】:2016-09-14 06:02:59
【问题描述】:

在当前的 react/redux 项目中使用 flowtype。
我在我的 actions.js 文件中定义了一个不相交的联合类型:

export type ArticleAction =
   { type: 'ARTICLE_SET_EDITION' }
  | { type: 'ARTICLE_BLABLA', blip: string };

然后在我的减速器中我有

import type { ArticleAction } from './actions';

[...]
 
const articlesReducer = (state: any = initialState, action: ArticleAction): any => {
  if (action.type === 'ARTICLE_BLABLA') {
    const test = action.blip.shoups;
    return test;
  }
 }

Flow 没有检测到问题。

但是!如果我直接在 reducer.js 中声明 ArticleAction,它会识别 action.blip.shoups 是无效的,因为 blip 是一个字符串。

知道我做错了什么吗? 谢谢

【问题讨论】:

  • actions.js 中有// @flow 吗?
  • 是的,我确实有 // @flow 在他们两个中

标签: javascript redux flowtype


【解决方案1】:

TL;DR Flow 在今天这样的情况下不会出错,但很可能在未来会出错。

这与导入/导出甚至联合类型无关,您可以将其简化为:

function method(val: 'foo') {
  if (val === 'bar') {
    // unreachable...
  }
}

Flow 可以看到这是一个不可能的细化,并且可以知道内部代码是不可达的。但是,Flow 在无法访问的情况下不会出错。今天,它只是将val 的值标记为该代码路径中的“空”类型,然后继续前进。

我们已开始为这种可达性分析奠定基础,并将使用它在未来版本的 Flow 中创建错误。

我们也可以使用可达性分析来测试穷举性,即:

function method(val: 'foo' | 'bar') {
  if (val === 'foo') {
    // ...
  } else if (val === 'bar') {
    // ...
  } else {
    // possibilities of val have been exhausted, this is unreachable...
  }
}

这些是常见的请求,我们正在处理它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2018-04-15
    相关资源
    最近更新 更多