Working around loss of support for type constraint being self

前端 未结 3 630
野性不改
野性不改 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:41

    promise() : T { return this; } it is very weak assumption that can be easily broken, because downcasting defined in a base class just cannot work for any sub-class

    For example in you case, if anyone defines class SuperChild extends Child {} then promise() of SuperChild is going to give you Child instead of SuperChild.

    Besides that here is how you can make it work the way it used to:

    class Base {
        public children : Array;
    
        constructor(
            private toSelf: () => T,
            private toBase: (something: T) => Base
        ) {
        }
    
    
        doAction() {
            this.toBase(this.children[0]).promise(); // used to work
        }
    
        promise() : T {
            return this.toSelf(); // 
        }
    }
    
    class Child extends Base {
        public myString: string;
    }
    
    function toThis() { return this; }
    
    new Child(toThis, x => x).promise().myString; // used to work
    

提交回复
热议问题