0

Angular Material2 & CDK make extensive use of coerceBooleanProperty in setters for boolean property inputs, but does not use Type consistently. Within their own code, in some cases we see both the getter return value and the setter argument as well as the internal property typed boolean. For example:

@Input()
get myProperty(): boolean { return this._myProperty; }
set myProperty(value: boolean) { this._myProperty = coerceBooleanProperty(value); }
private _myProperty: boolean = false;

In other cases we see only the setter argument typed (this seems to be the most common pattern in Material2 & CDK):

@Input()
get myProperty() { return this._myProperty; }
set myProperty(value: boolean) { this._myProperty = coerceBooleanProperty(value); }
private _myProperty = false;

Sometimes we see getter and setter typed as any:

@Input()
get myProperty(): any { return this._myProperty; }
set myProperty(value: any) { this._myProperty = coerceBooleanProperty(value); }
private _myProperty = false;

Sometimes there is no typing on either, but the internal property is deliberately typed boolean:

@Input()
get myProperty() { return this._myProperty; }
set myProperty(value) { this._myProperty = coerceBooleanProperty(value); }
private _myProperty: boolean = false;

It seems to me that the first example - typing both the getter return value and the setter argument as boolean - is the 'correct' approach, because this forces the application or library typescript code to use the property properly. But the lack of consistency in their own code use makes me wonder if there's something I haven't considered. Or perhaps it is merely a matter of newer implementations improving upon older implementations.

What is the preferred pattern here and why?

G. Tranter
  • 16,766
  • 1
  • 48
  • 68
  • I was wondering the same thing. I do not think the first example is the most logical one, because if the value passed to the setter would already be of type `boolean`, why would you need to call `coerceBooleanProperty`? the description of `coerceBooleanProperty` states the value is likely to be a string. So I would say `value: string | boolean` but I am not sure if besides those two types the property could also be null or undefined. – Kevkong Jan 15 '19 at 14:16
  • FWIW, I've settled on the first one. Although this makes the use of coerceBooleanPropoerty seem redundant from typescript, keep in mind that type is lost when compiled to plain old javascript, and that's where coerceBooleanProperty becomes useful. – G. Tranter Jan 15 '19 at 14:41
  • I am using `value: string | boolean. While the getter always returns a boolean, the setter can get two different types. If the property is set in template it would get a string, but if it is set using binding it gets a boolean. And ofc picking the most correct type is not necessary, because it is compiled to plain old js, but it can be helpful. – Kevkong Jan 15 '19 at 15:16

0 Answers0