readonly

TypeScript’s type system allows you to mark individual properties on an interface as readonly. This allows you to work in a functional way (unexpected mutation is bad):

  1. function foo(config: {
  2. readonly bar: number,
  3. readonly bas: number
  4. }) {
  5. // ..
  6. }
  7. let config = { bar: 123, bas: 123 };
  8. foo(config);
  9. // You can be sure that `config` isn't changed ?

Of course you can use readonly in interface and type definitions as well e.g.:

  1. type Foo = {
  2. readonly bar: number;
  3. readonly bas: number;
  4. }
  5. // Initialization is okay
  6. let foo: Foo = { bar: 123, bas: 456 };
  7. // Mutation is not
  8. foo.bar = 456; // Error: Left-hand side of assignment expression cannot be a constant or a read-only property

You can even declare a class property as readonly. You can initialize them at the point of declaration or in the constructor as shown below:

  1. class Foo {
  2. readonly bar = 1; // OK
  3. readonly baz: string;
  4. constructor() {
  5. this.baz = "hello"; // OK
  6. }
  7. }

Readonly

There is a type Readonly that takes a type T and marks all of its properties as readonly using mapped types. Here is a demo that uses it in practice:

  1. type Foo = {
  2. bar: number;
  3. bas: number;
  4. }
  5. type FooReadonly = Readonly<Foo>;
  6. let foo:Foo = {bar: 123, bas: 456};
  7. let fooReadonly:FooReadonly = {bar: 123, bas: 456};
  8. foo.bar = 456; // Okay
  9. fooReadonly.bar = 456; // ERROR: bar is readonly

Various Use Cases

ReactJS

One library that loves immutability is ReactJS, you could mark your Props and State to be immutable e.g.:

  1. interface Props {
  2. readonly foo: number;
  3. }
  4. interface State {
  5. readonly bar: number;
  6. }
  7. export class Something extends React.Component<Props,State> {
  8. someMethod() {
  9. // You can rest assured no one is going to do
  10. this.props.foo = 123; // ERROR: (props are immutable)
  11. this.state.baz = 456; // ERROR: (one should use this.setState)
  12. }
  13. }

You do not need to, however, as the type definitions for React mark these as readonly already (by internally wrapping the passed in generic types with the Readonly type mentioned above).

  1. export class Something extends React.Component<{ foo: number }, { baz: number }> {
  2. // You can rest assured no one is going to do
  3. someMethod() {
  4. this.props.foo = 123; // ERROR: (props are immutable)
  5. this.state.baz = 456; // ERROR: (one should use this.setState)
  6. }
  7. }

Seamless Immutable

You can even mark index signatures as readonly:

  1. /**
  2. * Declaration
  3. */
  4. interface Foo {
  5. readonly[x: number]: number;
  6. }
  7. /**
  8. * Usage
  9. */
  10. let foo: Foo = { 0: 123, 2: 345 };
  11. console.log(foo[0]); // Okay (reading)
  12. foo[0] = 456; // Error (mutating): Readonly

This is great if you want to use native JavaScript arrays in an immutable fashion. In fact TypeScript ships with a ReadonlyArray<T> interface to allow you to do just that:

  1. let foo: ReadonlyArray<number> = [1, 2, 3];
  2. console.log(foo[0]); // Okay
  3. foo.push(4); // Error: `push` does not exist on ReadonlyArray as it mutates the array
  4. foo = foo.concat([4]); // Okay: create a copy

Automatic Inference

In some cases the compiler can automatically infer a particular item to be readonly e.g. within a class if you have a property that only has a getter but no setter, it is assumed readonly e.g.:

  1. class Person {
  2. firstName: string = "John";
  3. lastName: string = "Doe";
  4. get fullName() {
  5. return this.firstName + this.lastName;
  6. }
  7. }
  8. const person = new Person();
  9. console.log(person.fullName); // John Doe
  10. person.fullName = "Dear Reader"; // Error! fullName is readonly

Difference from const

const

  1. is for a variable reference
  2. the variable cannot be reassigned to anything else.

readonly is

  1. for a property
  2. the property can be modified because of aliasing

Sample explaining 1:

  1. const foo = 123; // variable reference
  2. var bar: {
  3. readonly bar: number; // for property
  4. }

Sample explaining 2:

  1. let foo: {
  2. readonly bar: number;
  3. } = {
  4. bar: 123
  5. };
  6. function iMutateFoo(foo: { bar: number }) {
  7. foo.bar = 456;
  8. }
  9. iMutateFoo(foo); // The foo argument is aliased by the foo parameter
  10. console.log(foo.bar); // 456!

Basically readonly ensures that cannot be modified by me, but if you give it to someone that doesn’t have that guarantee (allowed for type compatibility reasons) they can modify it. Of course if iMutateFoo said that they do not mutate foo.bar the compiler would correctly flag it as an error as shown:

  1. interface Foo {
  2. readonly bar: number;
  3. }
  4. let foo: Foo = {
  5. bar: 123
  6. };
  7. function iTakeFoo(foo: Foo) {
  8. foo.bar = 456; // Error! bar is readonly
  9. }
  10. iTakeFoo(foo); // The foo argument is aliased by the foo parameter