Typescript: Suggestion: readonly constructor parameters

Created on 19 Mar 2016  路  8Comments  路  Source: microsoft/TypeScript

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.

Committed Fixed Suggestion

Most helpful comment

@leonyu Copying the arguments is not what I'm after. I'm asking for exactly the same semantics as readonly. No copying, no runtime checks. Just a shorthand for creating a readonly property, in the same way that adding public to a parameter is a shorthand way to create a public property.

All 8 comments

So would a readonly parameter be treated as a const within the body of its constructor?

No, it would simply be a shorthand for creating properties in the manner of constructor(public foo) { ... }, only we'd get a readonly property.

This can probably be implemented using a decorator on the function doing a defensive copy on the arguments. However, that would be a runtime check.

@leonyu Copying the arguments is not what I'm after. I'm asking for exactly the same semantics as readonly. No copying, no runtime checks. Just a shorthand for creating a readonly property, in the same way that adding public to a parameter is a shorthand way to create a public property.

+1

Makes a lot of sense. We'll include this along with the first release with readonly

Awesome, thanks!

Really glad this is implemented. In addition to the increased expressiveness, this allows a fair amount of code currently using accessibility modifiers for the sake of brevity to be written with clearer intent.

Was this page helpful?
0 / 5 - 0 ratings