Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active December 7, 2020 19:25
Show Gist options
  • Save rpivo/6fb3cb359192b0d0b249cc6d463d0c3f to your computer and use it in GitHub Desktop.
Save rpivo/6fb3cb359192b0d0b249cc6d463d0c3f to your computer and use it in GitHub Desktop.
Comparing Exact Object Types in Flow & TypeScript

Comparing Exact Object Types in Flow & TypeScript

Flow has something called exact object types. Without using it, you can specify properties that an object should have, but there's nothing stopping the object from having other properties besides the ones specified.

/* @flow */

const obj: {
  foo: string,
  bar: string,
} = {
  foo: 'foo',
  bar: 'bar',
  baz: 'baz', // not specified in the type, but this is fine
}

TypeScript won't allow this:

const obj: {
  foo: string,
  bar: string,
} = {
  foo: 'foo',
  bar: 'bar',
  baz: 'baz', // Type '{ foo: string; bar: string; baz: string; }' is not assignable to type '{ foo: string; bar: string; }'.
}

To get this same behavior in Flow, we can wrap the object type in pipe notation, which will prevent the object from having any extra properties other than the ones that are specified:

/* @flow */

const obj: {|
  foo: string,
  bar: string,
|} = {
  foo: 'foo',
  bar: 'bar',
  baz: 'baz', // Cannot assign object literal to `obj` because property `baz` is missing in object type [1] but exists in object literal [2].
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment