美文网首页
联合类型和类型保护

联合类型和类型保护

作者: 恍若如梦hzpeng | 来源:发表于2020-05-27 09:06 被阅读0次

类型保护

1、类型断言的方式

interface Bird {
  fly: boolean;
  sing: () => {};
}

interface Dog {
  fly: boolean;
  bark: () => {};
}


// 类型断言的方式
function trainAnial(animal: Bird | Dog) {   // 使用 | 就是联合类型 
  if (animal.fly) {
    // animal.sing();           // 错误 因为typescript不知道animal是否有sing方法
    (animal as Bird).sing();    // 正确 使用类型断言 
  } else {
    (animal as Dog).bark();
  }
}

2、in 语法做类型保护

interface Bird {
  fly: boolean;
  sing: () => {};
}

interface Dog {
  fly: boolean;
  bark: () => {};
}


function trainAnialSecond(animal: Bird | Dog) {
  if ('sing' in animal) {
    animal.sing();
  } else {
    animal.bark();
  }
}

3、typeof 方式

function add(first: string | number, second: string | number) {
    return first + second;  // 错误 string不能使用 + 操作符
}

// 正确
function add(first: string | number, second: string | number) {
  if (typeof first === 'string' || typeof second === 'string') {
    return `${first}${second}`;
  }
  return first + second;
}

4、instanceof 方式

class NumberObj {
  count: number;
}


// 错误
function addSecond(first: object | NumberObj, second: object | NumberObj) {
 return first.count + second.count; // count不一定存在,因为first和second可能是NumberObj或者其他对象
}

// 正确
function addSecond(first: object | NumberObj, second: object | NumberObj) {
  if (first instanceof NumberObj && second instanceof NumberObj) {
    return first.count + second.count;
  }
  return 0;
}

相关文章

  • 联合类型和类型保护

    类型保护 1、类型断言的方式 2、in 语法做类型保护 3、typeof 方式 4、instanceof 方式

  • 联合类型和类型保护

    联合类型,就是用 | 用算符,结合两个类型 联合类型变量去取值的时候,只能取到这几个类型共有的属性和方法。 如果调...

  • 高级TypeScript

    1、联合类型和类型保护 联合类型:一个变量可能有两种或两种以上的类型。 类型保护:联合类型的具体实例需...

  • TypeScript 08 - 高级类型

    交叉类型 联合类型 类型保护 可以为 null 的类型 字符串字面量类型 1. 交叉类型 交叉类型是将多个类型合并...

  • typescript中的类型保护

    类型保护: 当使用联合类型时, 我们必须尽量把当前值的类型收窄为当前值的实际类型,类型保护就是可执行运行时检查的一...

  • TypeScript中联合类型的类型保护

    在TypseScript中引入Redux给action加类型验证的时候我们考虑对于同一个请求的三个action的t...

  • 05-TypeScript-交叉类型-联合类型-类型保护

    交叉类型 格式: type1 & type2 & ... 交叉类型是将多个类型合并为一个类型 联合类型 格式: ...

  • typescript语法精讲一(笔记)

    - 使用联合类型 联合类型保证传入的是联合中的某一个类型的值即可 -可选类型补充 可选类型可以看作是 类型 和 u...

  • TS中type和interface类型守卫

    接口 通用函数类型 联合类型 联合类型技巧性使用场景 type 和 interface 区别 区别1: 定义类型范...

  • TypeScript06(类型断言 | 联合类型 | 交叉类型)

    联合类型 函数使用联合类型 交叉类型 多种类型的集合,联合对象将具有所联合类型的所有成员 类型断言 语法:值 as...

网友评论

      本文标题:联合类型和类型保护

      本文链接:https://www.haomeiwen.com/subject/rwmiahtx.html