question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

readonly property must be assigned in constructor

See original GitHub issue

TypeScript Version: 2.0.3

Code

class Person {
    public readonly name: string;
}
let p: Person = new Person();
// p.name ????

Expected behavior: Compilation error. Person.name is not initialized. So the Person class should be look like:

class Person {
    public readonly name: string;
    constructor(name: string) {
        this.name = name;
    }
}

let p: Person = new Person("Superman");

– or –

class Person {
    public readonly name: string = "Superman";
}

Actual behavior: Compilation success. No errors/warnings

Issue Analytics

  • State:open
  • Created 7 years ago
  • Reactions:3
  • Comments:9 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
superamadeuscommented, Nov 2, 2018

Seems like this is fixed by strict property initialization

1reaction
DanielRosenwassercommented, Oct 13, 2016

Good catch 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why can a read only property be assigned via constructor?
It can only be assigned in the constructor or in the initializer for the property declaration - just like a read-only field can...
Read more >
readonly keyword - C# Reference - Microsoft Learn
A readonly field can't be assigned after the constructor exits. This rule has different implications for value types and reference types:.
Read more >
PHP 8.1: Readonly Properties
Read-only property values can only be set from within the class itself, either from the constructor or another method. Once set, no further...
Read more >
PHP 8.1: readonly properties - Stitcher.io
You can see how the actual property doesn't get assigned a default value. The reason for not allowing default values on readonly properties,...
Read more >
PHP RFC: Readonly properties 2.0
A readonly property can only be initialized once, and only from the scope where it has been declared. Any other assignment or modification...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found