从 'this' 中省略两次嵌套 属性

omit twice nested property from 'this'

我正在尝试添加一个从对象类型中删除内部 属性 的方法,并且由于我无法更改的复杂基础 class,我遇到了以下问题: 我写了一个方法,应该在 属性 中进行强制转换(在本例中为名称) 但是 属性 ceo.name 仍然可以访问。 我相信发生这种情况是因为将没有首席执行官名称 属性 的类型添加到 this 只需要最大的分母 即 {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;
    }
}

也许你可以这样做:

type Ceo = { name: string };

class Company {
    addCeoNameType() {
        return this as this & {
            ceo: Ceo
        }
    }
    removeCeoNameType() {
        return this as unknown as Omit<this, 'ceo'> & { ceo: Omit<Ceo, 'name'> } ;
    }
}

class Foo {
    bar() {
        const catsInc = new Company();
        const catsIncWithCeoName = catsInc.addCeoNameType();
        catsIncWithCeoName.ceo.name;
        catsIncWithCeoName.removeCeoNameType().ceo.name;
                                                // ^ fails here
    }
}