readonly property must be assigned in constructor
See original GitHub issueTypeScript 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:
- Created 7 years ago
- Reactions:3
- Comments:9 (6 by maintainers)
Top 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 >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Seems like this is fixed by strict property initialization
Good catch 😃