TypeScript 里的类型保护本质上就是一些表达式,它们会在运行时检查类型信息,以确保在某个作用域里的类型是符合预期的。 要自定义一个类型保护,只需要简单地为这个类型保护定义一个函数即可,这个函数的返回值是一个类型谓词:
    我们来定义一个类型保护 isCat(),用以确保我们的类型是 Cat。

    1. interface Cat {
    2. climbingTrees();
    3. eat();
    4. }
    5. interface Dog {
    6. swim();
    7. eat();
    8. }
    9. function isCat(pet: Cat | Dog): pet is Cat {
    10. return (<Cat>pet).climbingTrees !== undefined;
    11. }
    12. // 调用类型保护函数 isCat 来确保 pet 类型
    13. if (isCat(pet)) {
    14. pet.climbingTrees();
    15. } else {
    16. pet.swim();
    17. }

    这里的 pet is Cat 是类型谓词。类型谓词的语法为 parameterName is Type 这种形式,其中 parameterName 必须是当前函数签名里的一个参数名。