Polymorphic this
types
A polymorphic this
type represents a type that is the subtype of the containing class or interface. This is called F-bounded polymorphism. This makes hierarchical fluent interfaces much easier to express, for example. Take a simple calculator that returns this
after each operation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class BasicCalculator { public constructor(protected value: number = 0) { } public currentValue(): number { return this .value; } public add(operand: number): this { this .value += operand; return this ; } public multiply(operand: number): this { this .value *= operand; return this ; } // ... other operations go here ... } let v = new BasicCalculator(2) .multiply(5) .add(1) .currentValue(); |
Since the class uses this
types, you can extend it and the new class can use the old methods with no changes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class ScientificCalculator extends BasicCalculator { public constructor(value = 0) { super (value); } public sin() { this .value = Math.sin( this .value); return this ; } // ... other operations go here ... } let v = new ScientificCalculator(2) .multiply(5) .sin() .add(1) .currentValue(); |
Without this
types, ScientificCalculator
would not have been able to extend BasicCalculator
and keep the fluent interface. multiply
would have returned BasicCalculator
, which doesn’t have the sin
method. However, with this
types, multiply
returns this
, which is ScientificCalculator
here.
Please login to continue.