为什么`{a:string}`不能流入`{a ?: string}` [英] Why can't `{ a: string }` flow into `{ a?: string }`

查看:65
本文介绍了为什么`{a:string}`不能流入`{a ?: string}`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出对象类型AB,除了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆