我怎样才能正确地键入带有 属性 对象条件的打字稿对象

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

我从 Typescript 开始,我尝试在 if 块中使用一个对象。在 if 中,我测试条件 - 如果一个 属性 存在,如果是这种情况,我可以将它用于 if 块,但 TS 编译器似乎不理解

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

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

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

Playground Link

支票

if ((pet as Fish).swim)

没有帮助 TS 推断 pet 的类型,因为每个 Fish 已经有 swim。使用 in 检查 属性 是否存在,并在 pet 上执行此操作,以便 pet 缩小到 Fish 并且可以有 swim 呼吁:

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

我认为你应该使用打字稿中的 Typeguard 功能 https://www.typescriptlang.org/docs/handbook/advanced-types.html

在您的容器中,如果您这样做,它应该可以工作:

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