我正在尝试添加一种从对象的类型中删除内部属性的方法,由于无法更改的复杂基类,我遇到以下问题:我写了一个方法,该方法应该强制转换属性(在这种情况下,名称)但是属性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;
}
}
也许您可以那样做: