省略'this'的两次嵌套属性

问题描述 投票:0回答:1

我正在尝试添加一种从对象的类型中删除内部属性的方法,由于无法更改的复杂基类,我遇到以下问题:我写了一个方法,该方法应该强制转换属性(在这种情况下,名称)但是属性ceo.name仍然可以访问。我相信会发生这种情况,因为向this添加不带CEO名称属性的类型只会占用最大的分母即{name:string} & {} == {name:string}

甚至还有解决此问题的方法吗?

class Company {
    ceo: {}
    addCeoNameType() {
        return this as this & {
            ceo: {
                name: string;
            }
        }
    }
    removeCeoNameType() {
        const ceoForType: this['ceo'] = null;
        return this as this & {
            ceo: Omit<typeof ceoForType, 'name'>;
        }
    }
}

class Foo {
    bar() {
        const catsInc = new Company();
        const catsIncWithCeoName = catsInc.addCeoNameType();
        catsIncWithCeoName.ceo.name;
        catsIncWithCeoName.removeCeoNameType().ceo.name;
    }
}
typescript typescript-typings typing
1个回答
2
投票

也许您可以那样做:

© www.soinside.com 2019 - 2024. All rights reserved.