user15350054
user15350054

Reputation:

How can i correctly type an object with typescript with condition on property object

I begin with Typescript and I tried to use an object inside the if block. In the if I test for the condition - if one property exists and if it's the case I can use it into the if block but TS compiler don't seems to understand

type Fish = {
    swim: () => void
}

type Bird = {
    fly: () => void
}

const test = function (pet: Fish | Bird) {
    if ((pet as Fish).swim) {
        pet.swim()
    }
}

Playground Link

Upvotes: 0

Views: 65

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370619

The check

if ((pet as Fish).swim)

does nothing to help TS infer the type of pet, because every Fish has swim already. Use in to check if the property exists instead, and do it on the pet, so that pet gets narrowed down to Fish and can have swim called on it:

const test = function (pet: Fish | Bird) {
    if ('swim' in pet) {
        pet.swim();
    }
};

Upvotes: 1

Related Questions