Skip to main content

Command Palette

Search for a command to run...

Read-only and optional class properties with TypeScript

Updated
1 min read
Read-only and optional class properties with TypeScript

Looking into creating a class in TypeScript, I came across two tidbits that struck me as really interesting. The first is the ability to mark a class property as read-only, i.e. once initialised, that property cannot be updated. You can do this by simply pre-pending readonly before the property name.

Secondly, you may define optional properties by appending a ? to the end of the property name. Easy as that!

class Child {
  readonly name: string;
  age: number;
  nickname?: string; // optional

  constructor(name: string, age: number, nickname?: string) {
    this.name = name;
    this.age = age;
    this.nickname = nickname;
  }
}

const alice = new Child("Alice", 10);
const bob = new Child("Robert", 5, "Bob");

console.log(alice.nickname, bob.nickname); // "undefined Bob"

More from this blog

Today I Learned

15 posts