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,
) {}
}