简体   繁体   中英

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

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

I think you should use Typeguard feature from typescript https://www.typescriptlang.org/docs/handbook/advanced-types.html

In your can if you do this it should be working:

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined
}
const test = function (pet: Fish | Bird) {
    if (isFish(pet)) {
        pet.swim()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM