TypeScript联合类型和类型保护

r囧r小猫 2023-07-23 06:57 81阅读 0赞

TypeScript在使用联合类型时,会遇到以下问题,需要进行类型保护,以保证逻辑严谨性。

  1. // 联合类型
  2. // 用于进行类型保护的方式
  3. // 1. as 语法 - 类型断言
  4. interface Bird {
  5. fly: boolean;
  6. sing: () => { };
  7. }
  8. interface Dog {
  9. fly: boolean;
  10. bark: () => { };
  11. }
  12. const trainAnimal = (animal: Bird | Dog) => {
  13. animal.fly ? (animal as Bird).sing() : (animal as Dog).bark();
  14. };
  15. // 2. in 语法
  16. const trainAnimalSecond = (animal: Bird | Dog) => {
  17. 'sing' in animal ? animal.sing() : animal.bark();
  18. };
  19. // 3. typeof 语法
  20. const addData = (first: string | number, second: string | number) => {
  21. return typeof first === 'string' || typeof second === 'string'
  22. ? `${ first}${ second}`
  23. : first + second;
  24. };
  25. // 4. instanceof 语法
  26. class NumberObj {
  27. constructor(public count: number) { }
  28. }
  29. const addDataSecond = (
  30. first: object | NumberObj,
  31. second: object | NumberObj
  32. ) => {
  33. return first instanceof NumberObj && second instanceof NumberObj
  34. ? first.count + second.count
  35. : 0;
  36. };

发表评论

表情:
评论列表 (有 0 条评论,81人围观)

还没有评论,来说两句吧...

相关阅读