Flowtype-制作密封的空对象 [英] Flowtype - making a sealed empty object

查看:62
本文介绍了Flowtype-制作密封的空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Flow的文档说:When you create an object without any properties, you create an unsealed object type in Flow.是否可以创建没有属性的密封对象?

Flow's docs say: When you create an object without any properties, you create an unsealed object type in Flow. Is it possible to create a sealed object without properties?

我的用例如下.我想将state初始化为一个空对象,并为状态指定以下类型:

My use case is as follows. I want to initialize state to an empty object, and give state the following type:

type EmployeesViewState = {|
  employeesRequest?: Request<Array<Employee>>,
  geosRequest?: Request<Array<Geo>>,
|};

当我尝试分配一个空对象时出现的错误是

The error I get when I try to assign an empty object is

 33:   state: EmployeesViewState = {};
                                   ^^ object literal. Inexact type is incompatible with exact type
 33:   state: EmployeesViewState = {};
              ^^^^^^^^^^^^^^^^^^ exact type: object type

当然,由于我还没有可用的请求,因此无法分配它们.我也无法将undefined分配给该对象,因为状态是用管道定义的,即它是一种确切的类型.

Of course, since I don't have the requests available yet, I cannot assign them. I also can't assign undefined to the object because the state is defined with pipes, i.e. it is an exact type.

我可以说const a: any = {}; state = a;来欺骗流程,但这似乎真的很棘手.还有其他解决此问题的方法吗?

I can trick flow by saying const a: any = {}; state = a; but that seems really hacky. Any other ways of tackling this issue?

推荐答案

这肯定是Flow的缺点之一.但是,它有一个相当简单的解决方法.只需将您的对象通过Object.freeze:

This is certainly one of Flow's warts. However, it has a fairly simple workaround. Just pass your object through Object.freeze:

Object.freeze({})

当然,这仅在您不打算对其进行突变的情况下才有效,但是我发现在这种情况下,我还是很少想要这么做.

Of course this only works if you weren't going to mutate it, but I find that in cases like this I rarely want to anyway.

这篇关于Flowtype-制作密封的空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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