profileRyan KesPGP keyI build stuffEmailGithubTwitterLast.fmMastodonMatrix

Readonly

Introduction

TypeScript's type system allows you to mark individual properties on interfaces, types and class properties as readonly.

Examples

interface

function foo(config: { readonly bar: number; readonly bas: number }) {
  // ..
}

let config = { bar: 123, bas: 123 }
foo(config)
// You can be sure that `config` isn't changed 🌹

type

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

class property

class Foo {
  readonly bar = 1 // OK
  readonly baz: string
  constructor() {
    this.baz = "hello" // OK
  }
}
type Foo = {
  bar: number
  bas: number
}

type FooReadonly = Readonly<Foo>

let foo: Foo = { bar: 123, bas: 456 }
let fooReadonly: FooReadonly = { bar: 123, bas: 456 }

foo.bar = 456 // Okay
fooReadonly.bar = 456 // ERROR: bar is readonly