手记

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

联合类型和类型保护

联合类型

联合类型使用 | 来表示

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';
}
0人推荐
随时随地看视频
慕课网APP