Skip to content

Suggestion: readonly constructor parameters #7590

Closed
@jahewson

Description

@jahewson

I've been using the new readonly properties feature (#6532) and have found it to be a very productive alternative to using getters or getWhatever() functions, or as is often the case, simply doing nothing to enforce read-only properties. However I'm really yearning for the ability to mark constructor parameters as readonly.

In 1.8 a common pattern for me is to write classes where all properties are public and readonly like so:

export class Foo {
  constructor(public bar: number,
              public baz: number) {}
}

But now with readonly I'm missing out unless I rewrite the above code to:

export class Foo {
  public readonly bar: number;
  public readonly baz: number;

  constructor(bar: number, baz: number) {
    this.bar = bar;
    this.baz = baz;
  }
}

Which is pretty cumbersome. What I'd really like to be able to write is:

export class Foo {
  constructor(public readonly bar: number,
              public readonly baz: number) {}
}

Right now I'm worried about hitting 2.0 and having to rewrite all my constructors just to take advantage of readonly. Because it's an advantage I definitely want to have.

Metadata

Metadata

Assignees

No one assigned

    Labels

    CommittedThe team has roadmapped this issueFixedA PR has been merged for this issueSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions