简体   繁体   English

如何在Flow类型中指定一个空对象?

[英]How to specify an empty object in Flow type?

Let's say I have a variable that can either be a JavaScript error object or an empty object, how would I specify the empty object in Flow? 假设我有一个可以是JavaScript错误对象或空对象的变量,我如何在Flow中指定空对象?

One possibility that I've tried as seen in various places (eg here ), looks like this: 我在各个地方(例如这里 )尝试过的一种可能性看起来像这样:

const err: Error | {||} = {};

But this gives the following flow error: 但是这会产生以下流量错误:

1: const exact: {||} = {};
                       ^ Cannot assign object literal to `exact` because inexact object literal [1] is incompatible with exact object type [2].
References:
1: const exact: {||} = {};
                       ^ [1]
1: const exact: {||} = {};
                ^ [2]

See it live here . 在这里看到 the || || notation is evidently shorthand for $Exact<> as explained here . 注释显然是速记$Exact<>作为解释在这里 So I can't see why exactly this is failing. 所以我不明白为什么这个失败了。

What it is saying is that the empty object I'm trying to assign to err is an "inexact object literal". 它所说的是我试图分配给err的空对象是一个“不精确的对象文字”。 I get that it's an object literal, which in fact does not match the "exact object type" of an empty object. 我知道它是一个对象文字,实际上与空对象的“确切对象类型”不匹配。

What I don't understand is why it is inexact. 我不明白的是为什么它不精确。 It seems pretty exact in that at runtime it is an empty object. 看起来非常精确,因为在运行时它是一个空对象。 Can someone explain the logic here and/or how it may be possible to specify that err is either an Error or an empty object? 有人可以解释这里的逻辑和/或如何指定errError还是空对象?

Try using $Shape<T> to specify an object with no properties: 尝试使用$Shape<T>指定没有属性的对象:

( Try ) 试试

type errOrObj = Error | $Shape<{||}>

const err: errOrObj = new Error("Blah")

const emptyObj: errOrObj = {}

const nonempty: errOrObj = {blah: 2} // Error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM