为什么`{a:string}`不能流入`{a ?: string}` [英] Why can't `{ a: string }` flow into `{ a?: string }`
本文介绍了为什么`{a:string}`不能流入`{a ?: string}`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出对象类型A
和B
,除了A
的属性是可选的以外,它们都相同...为什么不能在接受A
的地方使用B
?
Given object type A
and B
where both are the same except that A
's properties are optional… why can't be B
used in place where A
is accepted?
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
.
I think that Flow is trying to warn that if x
gets typed as an A
then it could potentially be modified such that it still fulfills the type definition of A
but does not fulfill the type definition of B
. For example, you could delete the a
property if x: A
, which would violate B
.
我通过创建A
的新只读"版本并将其转换为x
进行了测试.
I tested this by creating a new "read only" version of A
and casting x
to it.
type Required = { a: string};
type Optional = { a?: string };
type ReadOnlyOptional = $ReadOnly<Optional>;
const x: Required = { a: '' };
(x: Optional); // error
(x: ReadOnlyOptional); // no error!
这篇关于为什么`{a:string}`不能流入`{a ?: string}`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文