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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With