Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active December 9, 2020 01:38
Show Gist options
  • Save rpivo/2d80cc799f29ed6af985d0d2174466fd to your computer and use it in GitHub Desktop.
Save rpivo/2d80cc799f29ed6af985d0d2174466fd to your computer and use it in GitHub Desktop.
Comparing Read-Only & Write-Only Types in Flow & TypeScript

Comparing Read-Only & Write-Only Types in Flow & TypeScript

Flow and TypeScript have very similar means for declaring read-only types.

In TypeScript, if we want to create an object with immutable properties, we can do this:

const obj: Readonly<{
  foo: string,
  bar: string,
}> = {
  foo: 'foo',
  bar: 'bar',
}

console.log(obj)

obj.foo = 'hello' // error - Cannot assign to 'foo' because it is a read-only property.

The equivalent in Flow would be:

/* @flow */

const obj: $ReadOnly<{
  foo: string,
  bar: string,
}> = {
  foo: 'foo',
  bar: 'bar',
}

console.log(obj)

obj.foo = 'hello' // error - Cannot assign `'hello'` to `obj.foo` because property `foo` is not writable.

If we wanted to instead mark individual properties as read-only, we would do this in TypeScript:

const obj: {
  foo: string,
  readonly bar: string,
} = {
  foo: 'foo',
  bar: 'bar',
}

console.log(obj)

obj.foo = 'hello' // okay
obj.bar = 'goodbye' // error

In Flow, we would do:

/* @flow */

const obj: {
  foo: string,
  +bar: string,
} = {
  foo: 'foo',
  bar: 'bar',
}

console.log(obj)

obj.foo = 'hello' // okay
obj.bar = 'goodbye' // error

Flow's syntax is a little more terse for declaring read-only properties, though it may get confused with the + operator that is used to coerce a value into a number.

Flow also has write-only properties, which doesn't exist in TypeScript.

/* @flow */

const obj: {
  -foo: string,
  +bar: string,
} = {
  foo: 'foo',
  bar: 'bar',
}

const foo = obj.foo // error. obj.foo is not readable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment