5种在TypeScript中使用的类型保护

x33g5p2x  于2022-06-20 转载在 其他  
字(4.0k)|赞(0)|评价(0)|浏览(237)

**摘要:**在本文中,回顾了TypeScript中几个最有用的类型保护,并通过几个例子来了解它们的实际应用。

本文分享自华为云社区《如何在TypeScript中使用类型保护》,作者:Ocean2022。

类型保护是一种TypeScript技术,用于获取变量类型信息,通常使用在条件块语句中。类型守卫是返回布尔值的常规函数,接受一个类型并告诉TypeScript是否可以缩小到更具体的类型。类型保护具有唯一的属性,可以确保测试的值是根据返回的布尔值设置的类型。

TypeScript使用了一些内置的JavaScript操作符,比如typeof、instanceof和in操作符,这些操作符用于确定一个对象是否包含属性。类型保护可以让你指导TypeScript编译器在特定的上下文中推断出变量的特定类型,确保参数的类型与你所说的一致。

类型保护通常用于缩小类型,它非常类似于特征检测,允许您检测值的正确方法、原型和属性。因此,您可以轻松地找出如何处理该值。

有五种主要的方式来使用类型保护:

  • instanceof关键字
  • typeof关键字
  • in关键字
  • 等式收缩式保护器
  • 带有谓词的自定义类型保护

在本文中,我们将探索上面列出的 5 种方法。让我们开始吧!

instanceof 类型保护

Instanceof是一个内置类型保护器,可用于检查一个值是否是给定构造函数或类的实例。有了这个类型保护,我们可以测试一个对象或值是否派生自一个类,这对于确定实例类型的类型很有用。

instanceof类型保护的基本语法如下:

objectVariable instanceof ClassName;

在下面的例子中,我们看到了一个instanceof类型保护的例子:

interface Accessory {
    brand: string;
  }
  class Necklace implements Accessory{
    kind: string;
    brand: string;
    constructor(brand: string, kind: string) {    
      this.brand = brand;
      this.kind = kind;
    }
  }
  class bracelet implements Accessory{
    brand: string;
    year: number;
    constructor(brand: string, year: number) {    
      this.brand = brand;
      this.year = year;
    }
  }
  const getRandomAccessory = () =>{
    return Math.random() < 0.5 ?
      new bracelet('cartier', 2021) :
      new Necklace('choker', 'TASAKI');
  }
  let Accessory = getRandomAccessory();
  if (Accessory instanceof bracelet) {
    console.log(Accessory.year);
  }
  if (Accessory instanceof Necklace) {
    console.log(Accessory.brand);    
  }

上面的getRandomAccessory函数返回一个Necklace或bracelet对象,因为它们都实现了Accessory接口。Necklace和bracelet的构造函数签名是不同的,用instanceof比较两个构造函数签名可以有效地确定类型。

typeof 类型保护

typeof类型保护是用来确定变量的类型。typeof的类型保护据说是非常有限和浅薄的。它只能确定以下JavaScript能识别的类型:

  • Boolean
  • String
  • Bigint
  • Symbol
  • Undefined
  • Function
  • Number

对于这个列表之外的任何内容,typeof类型保护只返回object。

typeof类型保护可以用以下两种方式编写:

typeof v !== "typename"
#or 
typeof v === "typename"

typename可以是字符串、数字、符号或布尔值。

在下面的示例中,StudentId有一个string|number类型联合参数条目。我们看到,如果变量是string,则输出Student,如果是number,则输出Id。typeof类型保护符帮助我们从x参数中提取类型:

function StudentId(x: string | number) {
    if (typeof x == 'string') {
        console.log('Student');
    }
    if (typeof x === 'number') {
        console.log('Id');
    }
}
StudentId(`446`); //prints Student
StudentId(446); //prints Id

in 类型保护

in类型保护检查对象是否具有特定的属性,并使用该属性区分不同的类型它通常返回一个布尔值,表示该属性是否存在于该对象中。它用于其缩小范围,以及检查浏览器支持。

in类型保护的基本语法如下:

propertyName in objectName

在下面的例子中,in类型守卫检查 house 属性是否存在。如果存在,则返回布尔值true,如果不存在,则返回false。

"house" in { name: "test", house: { parts: "door" } }; // => true
"house" in { name: "test", house: { parts: "windows" } }; // => true
"house" in { name: "test", house: { parts: "roof" } }; // => true
"house" in { name: "test" }; // => false
"house" in { name: "test", house: undefined }; // => true

下面是in类型保护的另一个类似例子:

interface Pupil {
    ID: string;
  }
  interface Adult {
    SSN: number;
  }
  interface Person {
    name: string;
    age: number;
  }
  let person: Pupil | Adult | Person = {
    name: 'Britney',
    age: 6
  };
  const getIdentifier = (person: Pupil | Adult | Person) => {
    if ('name' in person) {
      return person.name;
    }
    else if ('ID' in person) {
      return person.ID
    }
    return person.SSN;
  }

等式收缩保护器

等式收缩保护器检查表达式的值。为了使两个变量相等,两个变量必须是同一类型的。如果一个变量的类型未知,但它等于另一个具有精确类型的变量,那么Typescript会使用该已知变量提供的信息来缩小第一个变量的类型:

function getValues(a: number | string, b: string) {
    if(a === b) {
        // this is where the narrowing takes place. narrowed to string
        console.log(typeof a) // string
    } else {
        // if there is no narrowing, type remains unknown
        console.log(typeof a) // number or string
    }
}

如果变量a等于变量b,那么两者必须具有相同的类型。在这种情况下,Typescript把它缩小到字符串。如果没有收缩,a的类型仍然不明确,因为它可以是数字或字符串。

带有谓词的自定义类型保护

创建一个自定义类型守卫通常是使用类型守卫的强大选项。当您通过自己编写来创建自定义类型保护时,可以检查的内容没有限制。但是,如果自定义类型保护被错误地编写,它可能会带来很多错误。因此,精度是关键

一个自定义类型保护的例子如下所示:

interface Necklace{
    kind: string;
    brand: string;
}
interface bracelet{
    brand: string;
    year: number;
}
type Accessory = Necklace | bracelet;

const isNecklace = (b: Accessory): b is Necklace => {
    return (b as Necklace).kind !== undefined
}
const Necklace: Accessory = {kind: "Choker", brand: "TASAKI"};
const bracelet: Accessory = {brand: "Cartier", year: 2021};
console.log(isNecklace(bracelet)) //Logs false
console.log(isNecklace(Necklace)) //Logs true

在上面的代码中,类型谓词b是Necklace,这会让TypeScript将类型缩减为Necklace,而不是只返回一个布尔值。

结尾

TypeScript类型保护有助于确保类型的值,改善整体的代码流。在本文中,我们回顾了TypeScript中几个最有用的类型保护,并通过几个例子来了解它们的实际应用。

大多数时候,您的用例可以使用instanceof类型保护、tyoeof的类型保护或in类型保护来解决,然而,您可以在绝对必要的时候使用自定义类型保护。

点击关注,第一时间了解华为云新鲜技术~

相关文章