Home > Mobile >  How to handle two generic objects in Type Script function
How to handle two generic objects in Type Script function

Time:12-12

I have a two generic types:

type Organization {
 id: String
 name: String
 type: String
}

type OrganizaationInput {
 id: String
 name: String
}

As you see difference is only one parameter (type). Both of this types were generated by codegen and I CAN'T change them. Also I have a function which can take this kind of objects as input parameters.

getCustomerFromOrganization(organization: Organization): Customers{
    ....
}

And my problem appears when I try to call this function with type OrganizationInput. How can I call the function getCustomerFromOrganization with both types?

p.s (organization: Organization | OrganizationInput) doesn't help

CodePudding user response:

Answer if found -

if ("type" in organization) {
    const { type } = organization;
    }

CodePudding user response:

You can use overloading:

type Organization = {
    id: String
    name: String
    type: String
}

type OrganizaationInput = {
    id: String
    name: String
}

function getCustomerFromOrganization(organization: OrganizaationInput): void
function getCustomerFromOrganization(organization : Organization | OrganizaationInput): void{
    ...
}

Link to playground

  • Related