Serge Esmanovich
Serge Esmanovich

Reputation: 147

How to get Type Partial without undefined on this case

I get error when i try call method

Cannot invoke an object which is possibly 'undefined'.

Partial<Pac & PacAdmin & PlayerParent> 
class Pac {
    getApi(role?: Role): Partial<Pac & PacAdmin & PlayerParent> {
            const apiProvider = {
                [Role.PacAdmin]: {
                    ...this,
                    ...new PacAdmin()
                },
                [Role.PlayerParent]: {
                    ...this,
                    ...new PlayerParent()
                }             
            }
    
            if (role && apiProvider[role]) {
                return apiProvider[role];
            }
    
            return this;
        }
    }

And class PacAdmin

class PacAdmin{
someMethod = ()=>{}
}

example:

const obj = new Pac();

obj.getApi(Role.PacAdmin).someMethod() - Error here

Playground

Upvotes: 1

Views: 496

Answers (1)

Mikhail Burshteyn
Mikhail Burshteyn

Reputation: 5012

The problem with the current implementation is that TypeScript has no way to know which attributes of Pac, PacAdmin or PlayerParent will be present in the returned object.

You can specify multiple overload signatures for the getApi method, so that the compiler will know the exact type of the returned value depending on the role parameter:

    getApi(role: Role.PacAdmin): Pac & PacAdmin
    getApi(role: Role.PlayerParent): Pac & PlayerParent
    getApi(role: undefined): Pac

See the updated playground.

Upvotes: 2

Related Questions