Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active January 19, 2021 19:48
Show Gist options
  • Save rpivo/7f93e29d24196dfef4c124be3da222fe to your computer and use it in GitHub Desktop.
Save rpivo/7f93e29d24196dfef4c124be3da222fe to your computer and use it in GitHub Desktop.
TypeScript Parameter Properties

TypeScript Parameter Properties

Rather than declaring class properties up front like this...

class ListNode {
  public val: number
  public next: ListNode | null

  constructor(val?: number, next?: ListNode | null) {
      this.val = val ?? 0
      this.next = next ?? null
  }
}

...we can simplify this by using TypeScript's parameter properties:

class ListNode {
  constructor(
      public val: number = 0,
      public next: ListNode | null = null,
    ) {}
}

Note that if we have other properties that won't be implemented with the constructor, we would have to declare those up front:

class ListNode {
  private someOtherProperty: number

  constructor(
      public val: number = 0,
      public next: ListNode | null = null,
    ) {}
}

References

TypeScript Handbook / Classes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment