1. interface Bird {
    2. fly: boolean
    3. sing:() => {}
    4. }
    5. interface Dog {
    6. fly: boolean
    7. bark:() => {}
    8. }
    9. // 类型断言的方式
    10. function trainAnimal(animal: Bird | Dog) {
    11. if (animal.fly) {
    12. (animal as Bird).sing()
    13. } else {
    14. (animal as Dog).bark()
    15. }
    16. }
    17. // in语法做类型保护
    18. function trainAnimal(animal: Bird | Dog) {
    19. if ('sing' in animal) {
    20. animal.sing()
    21. } else {
    22. animal.bark()
    23. }
    24. }
    25. //typeof语法来做类型保护
    26. function add(first: string | number, second: string | number) {
    27. if (typeof first === 'string' || typeof second === 'string') {
    28. return `${first}${second}`
    29. }
    30. return first + second
    31. }
    32. // 使用 instanceof 语法来做类型保护
    33. class NumberObj {
    34. count: number
    35. }
    36. function add(first: object | NumberObj, second: object | NumberObj) {
    37. if (first instanceof NumberObj && second instanceof NumberObj) {
    38. return first.count + second.count
    39. }
    40. return 0
    41. }