Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

One possibility that I've tried as seen in various places (e.g. 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. 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". 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?

like image 326
fraxture Avatar asked May 30 '18 21:05

fraxture


1 Answers

Try using $Shape<T> to specify an object with no properties:

(Try)

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

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

const emptyObj: errOrObj = {}

const nonempty: errOrObj = {blah: 2} // Error
like image 86
James Kraus Avatar answered Oct 11 '22 21:10

James Kraus