Search code examples
typescripttypescript-typingstyping

omit twice nested property from 'this'


I'm trying to add a method that removes an internal property from the type of an object and due to a complex base class that I cant change I have the following problem: I wrote a method that is supposed to cast out a cast in property (in this case, name) but the property ceo.name remains available to access. I believe this happens because adding a type without the ceo name property to this just takes the largest denominator i.e {name:string} & {} == {name:string}

is there even a way to solve this?

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;
    }
}

Solution

  • Maybe you could do it like that:

    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
        }
    }