Suggestion: allow get/set accessors to be of different types
It would be great if there was a way to relax the current constraint of requiring get/set accessors to have the same type. this would be helpful in a situation like this:
class MyClass {
private _myDate: moment.Moment;
get myDate(): moment.Moment {
return this._myDate;
}
set myDate(value: Date | moment.Moment) {
this._myDate = moment(value);
}
}
Currently, this does not seems to be possible, and I have to resort to something like this:
class MyClass {
private _myDate: moment.Moment;
get myDate(): moment.Moment {
return this._myDate;
}
set myDate(value: moment.Moment) {
assert.fail('Setter for myDate is not available. Please use: setMyDate() instead');
}
setMyDate(value: Date | moment.Moment) {
this._myDate = moment(value);
}
}
This is far from ideal, and the code would be much cleaner if different types would be allowed.
Thanks!
I can see how this would be nice here (and this has been requested before although I can't find the issue now) but it's not possible whether or not the utility is enough to warrant it. The problem is that accessors are not surfaced in .d.ts any differently than normal properties since they appear the same from that perspective. Meaning there's no differentiation between the getter and setter so there's no way to a) require an implementation use an accessor rather than a single instance member and b) specify the difference in types between the getter and setter.
Thank you for the quick reply, Dan. I'll follow the less elegant way. Thanks for the great work!
A JavaScript getter and setter with different types is perfectly valid and works great and I believe it is this feature's main advantage/purpose. Having to provide a setMyDate() just to please TypeScript ruins it.
Think also about pure JS libraries that will follow this pattern: the .d.ts will have to expose an union or any.
The problem is that accessors are not surfaced in .d.ts any differently than normal properties
Then this limitation should be fixed and this issue should stay open:
// MyClass.d.ts
// Instead of generating:
declare class MyClass {
myDate: moment.Moment;
}
// Should generate:
declare class MyClass {
get myDate(): moment.Moment;
set myDate(value: Date | moment.Moment);
}
// Or shorter syntax:
declare class MyClass {
myDate: (get: moment.Moment, set: Date | moment.Moment);
// and 'fooBar: string' being a shorthand for 'fooBar: (get: string, set: string)'
}
I realize this is just an opinion, but writing a setter such that a.x === y is not true immediately after a.x = y; is a giant red flag. How do consumers of a library like that know which properties have magic side effects and which don't?
How do [you] know which properties have magic side effects and which don't?
In JavaScript it can be un-intuitive, in TypeScript the tools (IDE + compiler) will complain. Why do we love TypeScript again? :)
A JavaScript getter and setter with different types is perfectly valid and works great and I believe it is this feature's main advantage/purpose.
This is arguing that JavaScript is weakly typed, so TypeScript should be weakly typed. :-S
This is arguing that JavaScript is weakly typed, so TypeScript should be weakly typed
~~C# allows it and that does not make this language weakly typed~~ C# does not allow get/set of different types.
~~C# allows it and that does not make this language weakly typed~~ C# does not allow get/set of different types.
:wink:
No one is arguing (as far as I can see) that accessors should be weakly typed, they are arguing that we should have the flexibility to define the type(s).
Often it is needed to copy a plain old object to object instances.
get fields(): Field[] {
return this._fields;
}
set fields(value: any[]) {
this._fields = value.map(Field.fromJson);
}
That is much nicer than the alternative and allows my setter to encapsulate the exact type of logic setters are made for.
@paulwalker the pattern you use there (a setter taking an any and a getter returning a more specific type) is valid today.
@danquirk Great to know, thank you! It looks like I just needed to update my IDE plugin compiler for ST.
@danquirk That doesn't seem to work according to the playground (or version 1.6.2): http://www.typescriptlang.org/Playground#src=%0A%0Aclass%20Foo%20%7B%0A%0A%20%20get%20items()%3A%20string%5B%5D%20%7B%0A%09%20%20return%20%5B%5D%3B%0A%20%20%7D%0A%20%20%0A%20%20set%20items(value%3A%20any)%20%7B%0A%09%20%20%0A%20%20%7D%0A%7D
I just tested with typescript@next (Version 1.8.0-dev.20151102), and also have an error.
~$ tsc --version
message TS6029: Version 1.8.0-dev.20151102
~$ cat a.ts
class A {
get something(): number {return 5;}
set something(x: any) {}
}
~$ tsc -t es5 a.ts
a.ts(2,2): error TS2380: 'get' and 'set' accessor must have the same type.
a.ts(3,2): error TS2380: 'get' and 'set' accessor must have the same type.
Ironically, after updating my Sublime linter, it no longer threw an error, which is using TypeScript 1.7.x. I've been assuming it is a forthcoming enhancement in 1.7+, so perhaps 1.8.0 regressed.
Even with the version of visual studio code (0.10.5 (December 2015)) that supports typescript 1.7.5 and with typescript 1.7.5 installed globally on my machine this is still a problem:

So what version this will be supported? Thanks
I think Dan was mistaken. The getter and the setter must be of identical type.
shame. would have been a nice feature for when writing page objects for use in protractor tests.
I would have been able to write a protractor test:
po.email = "[email protected]";
expect(po.email).toBe("[email protected]");
... by authoring a page object:
class PageObject {
get email(): webdriver.promise.Promise<string> {
return element(by.model("ctrl.user.email")).getAttribute("value")
}
set email(value: any) {
element(by.model("ctrl.user.email")).clear().sendKeys(value);
}
}
What about that code requires the setter to be of type any ?
The getter will return a webdriver.promise.Promise<string> yet the setter I want to assign a string value.
Maybe the following longer form of the protractor test makes it clearer:
po.email = "[email protected]";
var currentEmail : webdriver.promise.Promise<string> = po.email;
expect(currentEmail).toBe("[email protected]")
@RyanCavanaugh With the introduction of null annotations, this prevents code that allows calling a setter with null to set it to some default value.
class Style {
private _width: number = 5;
// `: number | null` encumbers callers with unnecessary `!`
get width(): number {
return this._width;
}
// `: number` prevents callers from passing in null
set width(newWidth: number | null) {
if (newWidth === null) {
this._width = 5;
}
else {
this._width = newWidth;
}
}
}
Could you consider atleast allowing the types to differ in the presence of | null and | undefined ?