在条件块中使用 typeof,instanceof,in,字面量类型,TypeScript 将会推导出在条件块中的变量类型。

  1. // typeof 示例
  2. let str = '123';
  3. if (typeof str === 'string') {
  4. str.substr(1)
  5. }
  6. // instanceof 示例
  7. class Foo {
  8. name!: string;
  9. play!: Function;
  10. }
  11. let foo = <Foo>{ name: 'Alex' }
  12. if (foo instanceof Foo) {
  13. foo.play()
  14. }
  15. // in 示例
  16. type Name = {
  17. name: string;
  18. }
  19. type Age = {
  20. age: number;
  21. }
  22. function isNameOrAge (q: Name | Age) {
  23. if ('name' in q) {
  24. q.name
  25. } else {
  26. q.age
  27. }
  28. }
  29. // 字面量类型保护
  30. type Bar1 = {
  31. kind: 'bar';
  32. name: string;
  33. }
  34. type Foo1 = {
  35. kind: 'foo';
  36. age: number;
  37. }
  38. function isBar1OrFoo1 (q: Bar1 | Foo1) {
  39. if (q.kind === 'bar') {
  40. q.name
  41. } else {
  42. q.age
  43. }
  44. }

自定义类型保护

  1. type Name = {
  2. name: string
  3. }
  4. type Age = {
  5. age: number
  6. }
  7. function isName (val: Name | Age): val is Name {
  8. return (val as Name).name !== undefined;
  9. }
  10. function isNameOrAge (q: Name | Age) {
  11. if (isName(q)) {
  12. q.name
  13. } else {
  14. q.age
  15. }
  16. }