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