自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

TypeScript的幾種類型保護(hù)方式

開發(fā) 前端
typeof? 是 JavaScript 中的一個(gè)操作符,TypeScript 使用它來檢查基本數(shù)據(jù)類型(如 string?, number?, boolean)。常用于保護(hù)原始類型。

TypeScript 的 類型保護(hù)(Type Guards)是一種確保在代碼運(yùn)行時(shí)可以更精確地處理特定類型的方法。通過類型保護(hù),TypeScript 能夠根據(jù)特定的條件(如值的屬性或操作方式)推斷變量的類型,從而減少類型錯(cuò)誤的可能性。

常見的幾種類型保護(hù)方式

  1. typeof 類型保護(hù)
  2. instanceof 類型保護(hù)
  3. in 操作符
  4. 自定義類型保護(hù)函數(shù)(Type Predicates)
  5. 字面量類型守護(hù)(Discriminated Unions)

1. typeof 類型保護(hù)

typeof 是 JavaScript 中的一個(gè)操作符,TypeScript 使用它來檢查基本數(shù)據(jù)類型(如 string, number, boolean)。常用于保護(hù)原始類型。

示例:

function printValue(value: string | number) {
  if (typeof value === "string") {
    console.log("The value is a string:", value.toUpperCase());
  } else {
    console.log("The value is a number:", value.toFixed(2));
  }
}

printValue("Hello"); // The value is a string: HELLO
printValue(123.456); // The value is a number: 123.46

在這個(gè)例子中,typeof 通過檢查 value 是 string 還是 number 來選擇合適的操作。

2. instanceof 類型保護(hù)

instanceof 檢查某個(gè)對(duì)象是否是另一個(gè)對(duì)象的實(shí)例(即其構(gòu)造函數(shù)的原型是否出現(xiàn)在該對(duì)象的原型鏈中)。適用于類實(shí)例的類型保護(hù)。

示例:

class Dog {
  bark() {
    console.log("Woof!");
  }
}

class Cat {
  meow() {
    console.log("Meow!");
  }
}

function makeSound(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    animal.bark(); // Safe to call bark() here
  } else {
    animal.meow(); // Safe to call meow() here
  }
}

const myDog = new Dog();
const myCat = new Cat();

makeSound(myDog); // Woof!
makeSound(myCat); // Meow!

在這個(gè)例子中,instanceof 檢查對(duì)象是否是 Dog 或 Cat 的實(shí)例,以選擇調(diào)用哪個(gè)方法。

3. in 操作符

in 操作符檢查對(duì)象中是否存在某個(gè)屬性,這對(duì)于聯(lián)合類型中可能包含不同屬性的情況非常有用。

示例:

interface Car {
  drive(): void;
}

interface Boat {
  sail(): void;
}

function move(vehicle: Car | Boat) {
  if ("drive" in vehicle) {
    vehicle.drive(); // Safe to call drive() here
  } else {
    vehicle.sail(); // Safe to call sail() here
  }
}

const car: Car = {
  drive() {
    console.log("Driving the car");
  },
};

const boat: Boat = {
  sail() {
    console.log("Sailing the boat");
  },
};

move(car);  // Driving the car
move(boat); // Sailing the boat

這里,in 操作符檢查 vehicle 是否有 drive 屬性,以此決定執(zhí)行 drive() 或 sail()。

4. 自定義類型保護(hù)函數(shù)(Type Predicates)

通過使用 類型謂詞(Type Predicates),可以創(chuàng)建自定義的類型保護(hù)函數(shù)。類型謂詞的語法是:param is Type,它表明如果函數(shù)返回 true,則 param 的類型為 Type。

示例:

interface Fish {
  swim(): void;
}

interface Bird {
  fly(): void;
}

function isFish(animal: Fish | Bird): animal is Fish {
  return (animal as Fish).swim !== undefined;
}

function moveAnimal(animal: Fish | Bird) {
  if (isFish(animal)) {
    animal.swim(); // TypeScript knows `animal` is a Fish
  } else {
    animal.fly(); // TypeScript knows `animal` is a Bird
  }
}

const fish: Fish = {
  swim() {
    console.log("The fish is swimming");
  },
};

const bird: Bird = {
  fly() {
    console.log("The bird is flying");
  },
};

moveAnimal(fish); // The fish is swimming
moveAnimal(bird); // The bird is flying

在這個(gè)例子中,isFish 是一個(gè)自定義類型保護(hù)函數(shù)。它檢查 animal 是否為 Fish,并根據(jù)類型來調(diào)用相應(yīng)的方法。

5. 字面量類型守護(hù)(Discriminated Unions)

字面量類型守護(hù)是通過在聯(lián)合類型中引入一個(gè)區(qū)分字段(discriminant field)來實(shí)現(xiàn)的。通常在每個(gè)類型中使用一個(gè)固定的字面量屬性來進(jìn)行類型保護(hù)。

示例:

interface Square {
  kind: "square";
  size: number;
}

interface Rectangle {
  kind: "rectangle";
  width: number;
  height: number;
}

interface Circle {
  kind: "circle";
  radius: number;
}

type Shape = Square | Rectangle | Circle;

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case "square":
      return shape.size * shape.size;
    case "rectangle":
      return shape.width * shape.height;
    case "circle":
      return Math.PI * shape.radius * shape.radius;
    default:
      return 0;
  }
}

const square: Square = { kind: "square", size: 5 };
console.log(getArea(square)); // 25

在這個(gè)例子中,Shape 類型是由 Square, Rectangle 和 Circle 組成的聯(lián)合類型,它們都有 kind 字段,通過這個(gè)字段我們可以區(qū)分出當(dāng)前的具體類型并相應(yīng)處理。

總結(jié)

TypeScript 提供了多種類型保護(hù)方式來安全地處理聯(lián)合類型或復(fù)雜的類型結(jié)構(gòu):

  • typeof: 用于檢查基本數(shù)據(jù)類型 (string, number, boolean)。
  • instanceof: 用于檢查對(duì)象是否是某個(gè)類的實(shí)例。
  • in: 用于檢查對(duì)象是否具有某個(gè)屬性。
  • 自定義類型保護(hù)函數(shù): 通過類型謂詞創(chuàng)建自定義的類型保護(hù)函數(shù)。
  • 字面量類型守護(hù)(Discriminated Unions): 使用區(qū)分字段來區(qū)分聯(lián)合類型中的不同類型。

這些類型保護(hù)方式可以幫助你在 TypeScript 中更安全地編寫代碼,并減少運(yùn)行時(shí)錯(cuò)誤。

責(zé)任編輯:武曉燕 來源: 宇宙一碼平川
相關(guān)推薦

2022-06-27 09:45:22

MySQL索引

2011-12-26 15:58:01

枚舉

2010-03-12 17:29:16

Python模塊

2021-12-20 23:24:40

前端測(cè)試開發(fā)

2020-09-23 07:47:14

Java方式類型

2023-07-04 15:11:30

TypeScript類型保護(hù)

2021-09-09 13:53:08

區(qū)塊鏈加密貨幣技術(shù)

2022-02-25 14:06:01

區(qū)塊鏈生態(tài)系統(tǒng)技術(shù)

2021-03-11 14:46:05

C++類型轉(zhuǎn)換語言

2020-12-30 07:55:37

C++轉(zhuǎn)換類型

2022-08-31 07:04:50

Bean作用域

2022-03-11 15:40:49

PaaS云服務(wù)

2021-06-15 09:12:19

TypeScriptTypeScript Javascript

2021-05-07 16:19:36

異步編程Java線程

2010-09-25 14:48:55

SQL連接

2021-01-19 11:56:19

Python開發(fā)語言

2022-02-25 09:06:02

TypeScripnever工具

2021-07-27 06:06:34

TypeScript語言運(yùn)算符

2024-03-12 08:29:28

C++類型轉(zhuǎn)換方式

2021-06-07 14:05:53

物聯(lián)網(wǎng)IOT物聯(lián)網(wǎng)技術(shù)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)