美文网首页TypeScript
TypeScript in操作符缩小

TypeScript in操作符缩小

作者: 我的袜子都是洞 | 来源:发表于2022-12-29 08:24 被阅读0次

TypeScript in操作符缩小

语法:

"valuse" in x

实例:

type Fish = { swim: () => void }
type Bird = { fly: () => void }
type Human = { swim?: () => void; fly?: () => void }

type Animal = Fish | Bird | Human

function move(animal: Animal) {
    if ("swim" in animal) {
        // animal: Fish | Human
        return (animal as Fish).swim();
    }
    return (animal as Bird).fly();
}

相关文章

网友评论

    本文标题:TypeScript in操作符缩小

    本文链接:https://www.haomeiwen.com/subject/qwmgfdtx.html