【问题标题】:I don't understand incompatible type error in assignment我不明白分配中的不兼容类型错误
【发布时间】:2017-12-05 03:48:07
【问题描述】:

谁能解释我为什么会出现流量错误

object type (This type is incompatible with object type Indexable signature is incompatible:)

对于最后一行的赋值

const plain: { [key: string]: string } = { prop: '' };
type TestType = { [key: string]: string | number };
const testVar: TestType = plain;

如果我删除普通...的类型规范,我没有错误

非常感谢!

【问题讨论】:

  • 似乎 Flow 无法看到一个是另一个的子集,一个是 string,另一个是 string | number。它可以作为简单类型,但这里使用的键/值哈希映射类型是一种特殊构造。还有一个限制 - 查看 Flow 的 Github“问题”部分,人们每天都会发现五个新的限制(没有一个被解决并且永远保持开放的问题)。随意将您的问题添加到不断增长的列表中。 我自己实际上使用 Flow,我只是接受该工具的功能受到严重限制。 我也将plain 声明为TestType 类型!
  • 感谢您的快速回复。我已按照您的建议提交了一个问题 (github.com/facebook/flow/issues/5458)。如果你写你的评论作为答案,我很乐意接受。

标签: flowtype


【解决方案1】:

Vladimir Kurchatkin 在我在 github (https://github.com/facebook/flow/issues/5458) 上打开的问题中回答了这个问题:

默认情况下对象是不变的。你可以像这样使它成为协变的:

const plain: { [key: string]: string } = { prop: '' };
type TestType = { +[key: string]: string | number };
const testVar: TestType = plain;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    相关资源
    最近更新 更多