|
| 1 | +/** |
| 2 | + * This module demonstrates covariant overrides support in jsii. |
| 3 | + * |
| 4 | + * Covariant overrides allow derived classes to override methods with more specific return types. |
| 5 | + * This was previously not supported because C# didn't allow it, but newer versions of C# (9.0+) do. |
| 6 | + */ |
| 7 | + |
| 8 | +/** Base class in the inheritance hierarchy */ |
| 9 | +export class ASuperclass {} |
| 10 | + |
| 11 | +/** Derived class that extends Superclass */ |
| 12 | +export class BSubclass extends ASuperclass {} |
| 13 | + |
| 14 | +/** Further derived class that extends Subclass */ |
| 15 | +export class CSubSubclass extends BSubclass {} |
| 16 | + |
| 17 | +export interface IBase { |
| 18 | + readonly something: ASuperclass; |
| 19 | +} |
| 20 | + |
| 21 | +/** Base class with methods and properties that will be overridden with covariant return types */ |
| 22 | +export class OriginalBase implements IBase { |
| 23 | + public readonly something: ASuperclass = new ASuperclass(); |
| 24 | + public createSomething(): ASuperclass { |
| 25 | + return new ASuperclass(); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +/** Middle class in the inheritance chain - doesn't override anything */ |
| 30 | +export class SomethingInTheMiddle extends OriginalBase { |
| 31 | + public addUnrelatedMember = 3; |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * Derived class that demonstrates covariant overrides. |
| 36 | + * |
| 37 | + * Both property and method overrides are covariant and will work in C# 9.0+ |
| 38 | + * when the covariant-overrides feature is enabled. |
| 39 | + */ |
| 40 | +export class TheEnd extends SomethingInTheMiddle { |
| 41 | + // This property override is covariant (SubSubclass extends Superclass) |
| 42 | + public readonly something: CSubSubclass = new CSubSubclass(); |
| 43 | + |
| 44 | + // This method override is covariant and will work in C# 9.0+ |
| 45 | + public createSomething(): CSubSubclass { |
| 46 | + return new CSubSubclass(); |
| 47 | + } |
| 48 | +} |
0 commit comments