使用联合类型,只会提示共有的方法
    image.png
    解决联合类型的几种方式:
    联合类型和类型保护 - 图2
    对 in 语法的理解
    instanceof 语法

    1. interface Bird {
    2. fiy: boolean;
    3. sing: () => {};
    4. }
    5. interface Dog {
    6. fiy: boolean;
    7. bark: () => {};
    8. }
    9. // 解决联合类型的几种方式:
    10. // 类型断言的方式
    11. function trainAnial(animal: Bird | Dog) {
    12. if (animal.fiy) {
    13. (animal as Bird).sing();
    14. } else {
    15. (animal as Dog).bark();
    16. }
    17. }
    18. // in 语法来做类型保护
    19. function trainAnialSecond(animal: Bird | Dog) {
    20. if ("sing" in animal) {
    21. animal.sing();
    22. } else {
    23. animal.bark();
    24. }
    25. }
    26. // typeof 语法来做类型保护
    27. function add(first: number | string, second: number | string) {
    28. if (typeof first === "string" || typeof second === "string") {
    29. return `${first}${second}`;
    30. }
    31. return first + second;
    32. }
    33. // instanceof 语法来做类型保护(只有class才具备用instanceof操作符
    34. class NumberObj {
    35. count!: number;
    36. }
    37. function addSecond(first: object | NumberObj, second: object | NumberObj) {
    38. if (first instanceof NumberObj && second instanceof NumberObj) {
    39. return first.count + second.count;
    40. } else {
    41. return 0;
    42. }
    43. }