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

采得百花成蜜后,为谁辛苦为谁甜。这篇文章主要讲述5种在TypeScript中使用的类型保护相关的知识,希望能为你提供帮助。

摘要:在本文中,回顾了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.brandbrand;
this.kindkind;


class bracelet implements Accessory
brand string;
year number;
constructor(brand string, year number)
this.brandbrand;
this.yearyear;


const getRandomAccessory()
return Math.random()0.5
new bracelet(cartier, 2021)
new Necklace(choker, TASAKI);

let AccessorygetRandomAccessory();
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 stringnumber)
if (typeof xstring)
console.log(Student);

if (typeof xnumber)
console.log(Id);


StudentId(`446`); //prints Student
StudentId(446); //prints Id

in 类型保护
??in??类型保护检查对象是否具有特定的属性,并使用该属性区分不同的类型。它通常返回一个布尔值,表示该属性是否存在于该对象中。它用于其缩小范围,以及检查浏览器支持。
??in??类型保护的基本语法如下:
??propertyName in objectName??
在下面的例子中,in类型守卫检查  ??house??  属性是否存在。如果存在,则返回布尔值true,如果不存在,则返回false。
"house" inname "test", houseparts "door"; // => true
"house" inname "test", houseparts "windows"; // => true
"house" inname "test", houseparts "roof"; // => true
"house" inname "test" ; // => false
"house" inname "test", house undefined ; // => true

下面是??in??类型保护的另一个类似例子:
interface Pupil
ID string;

interface Adult
SSN number;

interface Person
name string;
age number;

let person PupilAdultPerson
name Britney,
age 6
;
const getIdentifier(person PupilAdultPerson)
if (name in person)
return person.name;

else if (ID in person)
return person.ID

return person.SSN;

等式收缩保护器
等式收缩保护器检查表达式的值。为了使两个变量相等,两个变量必须是同一类型的。如果一个变量的类型未知,但它等于另一个具有精确类型的变量,那么Typescript会使用该已知变量提供的信息来缩小第一个变量的类型:
function getValues(a numberstring, b string)
if(ab)
// 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 AccessoryNecklacebracelet;

const isNecklace(b Accessory) b is Necklace
return (b as Necklace).kindundefined

const Necklace Accessorykind "Choker", brand "TASAKI";
const bracelet Accessorybrand "Cartier", year 2021;
console.log(isNecklace(bracelet)) //Logs false
console.log(isNecklace(Necklace)) //Logs true

在上面的代码中,类型谓词??b??是??Necklace??,这会让TypeScript将类型缩减为??Necklace??,而不是只返回一个布尔值。
结尾
TypeScript类型保护有助于确保类型的值,改善整体的代码流。在本文中,我们回顾了TypeScript中几个最有用的类型保护,并通过几个例子来了解它们的实际应用。
大多数时候,您的用例可以使用??instanceof???类型保护、??tyoeof???的类型保护或??in??类型保护来解决,然而,您可以在绝对必要的时候使用自定义类型保护。

【5种在TypeScript中使用的类型保护】?点击关注,第一时间了解华为云新鲜技术~?

    推荐阅读