• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

typescript(四)类型保护

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

类型保护指的是确认分支作用域中的类型。可以更具体的调用参数上的属性和方法。

1. 基本类型保护

function first(a: number|string|boolean):number {
  if(typeof a === 'number') {
    return a;
  } else if(typeof a === 'string') {
    return a.length;
  } else {
    return 0;
  }
}

2. 类保护-instanceof

class Animal{
  name: string = '';
}
class Bird extends Animal {
  sing: string = 'song';
}
class Dog extends Animal {
  eat: string = 'bone';
}
function second(animal: Animal) {
  if (animal instanceof Bird) {
    return animal.name;
  } else if(animal instanceof Dog) {
    return animal.eat;
  } else {
    return animal.name;
  }
}

3. null保护

开启了strictNullChecks, 则不能直接调用变量可能为null的变量上的方法和属性。

1.  使用!

function t(str: string|null) {
  return str!.length
}

2. 使用 ||

function t1(str: string|null) {
  str = str || '';
  return str.length
}

3. 使用链判断运算符-?.

⚠️该运算符处于stage1阶段,现不能直接使用;需要安装插件

let a = {b:0};
let c = a?.b; 
// 原理: 如果变量为null,或者该变量不存在某属性
if (!a) {
  return undefined
} else {
  return a.b
}

4. 联合类型保护

1. 可以通过同名属性的不同值进行区分

interface WarningButton {
  text: 'warning',
  color: 'yellow'
}
interface DangerButton {
  text: 'danger',
  do: 'be careful'
}
type Button = WarningButton | DangerButton;
function chooseBtn(button: Button) {
  if(button.text === 'warning') {
    return button.color;
  } else if(button.text === 'danger') {
    return button.do;
  }
}

2. 可以通过各自的特有属性进行区分-in

interface WarningBtn {
  text: string,
  color: string
}
interface DangerBtn {
  text: string,
  do: string
}
type Btn = WarningBtn | DangerBtn;
function ChooseBtn(btn: Btn) {
  if ('color' in btn) {
    return btn.color;
  } else if('do' in btn) {
    return btn.do;
  }
}

3. 自定义实现类型保护-is

当方法1,2都不能满足条件的时候

 interface Bird {
   legs: number
 }
 interface Dog {
   legs: number
 }
 type Animals = Bird | Dog;
 function isBird(x: Animals):x is Bird {
   return x.legs === 2;
 } 
 function diffAni(x: Animals) {
   if(isBird(x)) {
     // to be Bird
   } else {
     // to be  Dog
   }
 }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
从C#到TypeScript - 高级类型发布时间:2022-07-18
下一篇:
在 Ionic2 TypeScript 项目中导入第三方 JS 库发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap