javascript - 为什么 `{ a: string }`不能流入 `{ a?: string }`

标签 javascript flowtype

给定对象类型 AB 两者除了 A 的属性是可选的之外是相同的......为什么不能 B 用于 A 被接受的地方?

type A = { a?: string };
type B = { a: string };

const x: B = { a:'…' };

// …string is incompatible with undefined in property `a`
(x: A)

Flow try link here

最佳答案

我认为 Flow 试图警告如果 x 被键入为 A 那么它可能会被修改以使其仍然满足 的类型定义>A 但不满足 B 的类型定义。例如,如果 x: A,您可以删除 a 属性,这将违反 B

我通过创建一个新的“只读”版本的 A 并将 x 转换为它来测试它。

type Required = { a: string};
type Optional = { a?: string };
type ReadOnlyOptional = $ReadOnly<Optional>;

const x: Required = { a: '' };
(x: Optional); // error
(x: ReadOnlyOptional); // no error!

Try Flow

关于javascript - 为什么 `{ a: string }`不能流入 `{ a?: string }`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57255895/

相关文章:

javascript - Flow 中所有键具有相同类型的对象

reactjs - 在不传递任何 props 的情况下实例化组件时出现流错误 "props is incompatible with empty"

javascript - 如何在 JS/React 中下载 mp4 视频?

javascript - JSON.stringify 缺少属性

javascript - React-路由器 : Achieving the same goal of <IndexRoute> in v4

javascript - Firefox 17.0.1 扩展无法访问文件

javascript - 流程中的未细化类型转换,在对象(以及所述对象的数组)中使用嵌套类型

javascript - 这种说法 `const types = ({ editor }: { editor: Editor }) => {}` 是什么意思?

javascript - 在 JQuery $.when 调用中处理可变数量的延迟请求的更好方法?

ecmascript-6 - FlowType 是否支持混合或组合?