Working around loss of support for type constraint being self

前端 未结 3 626
野性不改
野性不改 2021-01-05 06:07

This is something I\'ve been doing in older versions of TypeScript and I use this method in C#, but it doesn\'t work in the latest 1.0 version of TypeScript.

Here\'s

3条回答
  •  清酒与你
    2021-01-05 06:35

    I accepted Steve's answer because he suggested to use Base>, but I wanted to keep a copy of the code change that fixed the problem on Stack Overflow:

    class Base> { // 1. Set as any
        children: Array;
    
        doAction() {
            this.children[0].promise();
        }
    
        promise(): T {
            return  this; // 2. cast to any
        }
    }
    
    class Child extends Base {
        public myString: string;
    }
    
    new Child().promise().myString;
    

    This requires a cast to any, but it's not so bad since it's only in the base class. This change doesn't affect anything using the Child or Base classes, so overall it was a very ideal alternative.


    Update: In TS 1.7+ this can be done using a polymorphic this:

    class Base {
        children: Array;
    
        doAction() {
            this.children[0].promise();
        }
    
        promise(): this {
            return this;
        }
    }
    
    class Child extends Base {
        public myString: string;
    }
    
    new Child().promise().myString;
    

提交回复
热议问题