继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【十月打卡】第57天 TypeScript(13)

康遇
关注TA
已关注
手记 76
粉丝 3
获赞 9

联合类型和类型保护

联合类型

联合类型使用 | 来表示

const value = string | number;

类型保护

  • 类型断言 as
  • in
interface Bird {
 fly: boolean;
 sing: () => void;
}

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

// 类型断言 as
function handleAnimal(animal: Bird | Dog){
 if(animal.fly){
   (animal as Bird).sing()
 }else{
   (animal as Dog).bark()
 }
}

// in
function judgeAnimal(animal: Bird | Dog) {
 if ('sing' in animal) {
   animal.sing()
 } else {
   animal.bark();
 }
}
  • typeof
function total(first: string | number, second: string | number) {
  if (typeof first === 'string' || typeof second === 'string') {
    return `${first}${second}`;
  }
  return first + second;
}
  • instanceof
class Person {
  constructor(public name: number) {}
}

class Purchase {
  constructor(public count: number) {}
}

function addCount(first: Person | Purchase, second: Person | Purchase) {
  if (first instanceof Purchase && second instanceof Purchase) {
    return first.count + second.count;
  }
  return 100;
}

枚举类型 enum

介绍

  • enum 适用于有多种状态的场景判断
  • enum第一个默认是0,后面的如果没有指定,会在前面基础上加1
  • enum是可以双向访问
enum Network {
  ONLINE = 1,
  G4,
  G3,
  OFFLINE,
};
console.log(Network.ONLINE)  // 1
console.log(Network[1])  // 'ONLINE'

示例

  • 正常的js代码
const Network = {
  ONLINE: 0,
  G4: 1,
  G3: 2,
  OFFLINE: 3,
};

function getNetworkStatus(status: number) {
  if (status === Network.ONLINE) {
    return 'online';
  } else if (status === Network.G4) {
    return '4g';
  } else if (status === Network.G3) {
    return '3g';
  } else if (status === Network.OFFLINE) {
    return 'offline';
  }
  return 'else';
}
  • ts中使用enum来改造
enum Network  {
  ONLINE,
  G4,
  G3,
  OFFLINE,
};

function getNetworkStatus(status: number) {
  if (status === Network.ONLINE) {
    return 'online';
  } else if (status === Network.G4) {
    return '4g';
  } else if (status === Network.G3) {
    return '3g';
  } else if (status === Network.OFFLINE) {
    return 'offline';
  }
  return 'else';
}
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP