Cannot Optionalize Class Getters
See original GitHub issueTypeScript Version: 2.2.1
Code
class Person {
firstName: string;
lastName: string;
get fullName?() {
return this.firstName + ' ' + this.lastName;
}
}
Expected behavior:
Since fullName
is optional the following should work:
const Me: Person = {
firstName: 'Foo',
lastName: 'Bar'
}
Actual behavior:
A syntax error occurs on this line get fullName?() {
I’m not sure if omitting the ability to optionalize getters was by design or not. If it was by design, I’d love to know the reasoning behind it.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:45
- Comments:31 (6 by maintainers)
Top Results From Across the Web
typescript optional property with a getter - Stack Overflow
In a class that implements an interface with an optional readonly property, the class may leave off the getter. See this answer get...
Read more >Returning an optional in getters - Code is poetry
A practice I've used recently and found quite helpful is to wrap the return type of newly created getters inside an Optional.
Read more >getter - JavaScript - MDN Web Docs - Mozilla
The get syntax binds an object property to a function that will be called when that property is looked up. It can also...
Read more >Using Optional with Jackson - Baeldung
In this case, isPresent() is a public getter on the Optional class. This means it will be serialized with a value of true...
Read more >Swift properties / getters setters | Apple Developer Forums
public class Person { private var _id: Int = 0 private var _lastName: String ... _id; } set { if newValue < 0...
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
@mhegazy Like bradenhs said, class methods can be made optional, as shown in this merged PR: https://github.com/Microsoft/TypeScript/pull/8625
As can be seen, it’s an optional method that also has a body/implementation specified.
That’s the same thing we’d like for class getters/setters, like so:
However, this doesn’t compile currently, which seems inconsistent when class methods work with it fine.
@mhegazy seems inconsistent to allow (bodied) optional methods but not getters. Thoughts?