给定对象类型 A
和 B
两者除了 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 试图警告如果 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!
关于javascript - 为什么 `{ a: string }`不能流入 `{ a?: string }`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57255895/