Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand TypeScript federated types, cross types and type protection

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to understand TypeScript joint types, cross types and type protection". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Joint type

The so-called federated type is to define some types. The defined variable only needs to satisfy any type. The federated type uses | definition. The sample code is as follows:

/ / pass | symbol defines the union type let value: number | boolean | string = 'one bowl week' value = 18

In the above code, we define a value variable, which can be of type number, boolean, or string.

two。 Cross type

Introduces the federation type, and then introduces the crossover type that is particularly similar.

The so-called cross type is that it needs to satisfy all types, and the cross type uses the & symbol definition.

The sample code is as follows:

/ / define three common interface types interface Name {name: string} interface Age {age: number} interface Hobby {hobby: string} / / define an object that is the joint type of the above three objects let person: Name & Age & Hobby = {/ / if you assign one less type, you will throw an exception name: 'bowl week', age: 18, hobby: 'coding',} 3. Type protection

Now we have a requirement: get the first number in an array of any type.

The implementation code is as follows:

/ / define an array containing number or string const arr: (number | string) [] = [1, 'number'] / / the traversal array returns the first number const getValue: (arr: (number | string) []) = > number = (arr: (number | string) [],): number = > {for (let I = 0; I)

< arr.length; i++) { // 如果当前值转换为数字时候不是一个 NaN 则返回 if (!isNaN(Number(arr[i]))) { return arr[i] // 不能将类型"string | number"分配给类型"number"。 } }} 上述代码中return时并不知道返回的是不是一个number类型。所以将会抛出异常。 上述功能可以通过类型断言来完成,示例代码如下: const getValue: (arr: (number | string)[]) =>

Number = (arr: (number | string) [],): number = > {for (let I = 0; I)

< arr.length; i++) { // 如果当前值转换为数字时候不是一个 NaN 则返回 if (!isNaN(Number(arr[i]))) { return arr[i] as number // 告诉 编译器 我返回的就是一个 number } }} 什么是类型断言请参考:类型断言 如果使用类型断言来说明,如果想要的数据类型不一样时,就会显得比较繁琐。这个时候就需要类型保护来完成该功能, 类型保护主要分为以下三种: 3.1自定义类型保护 自定义类型保护的方式就是定义一个函数,该函数是的返回结构是一个parameterName is type的形式,该形式是一个类型谓词 。parameterName必须是来自于当前函数参数里的一个参数名。 示例代码如下: // 使用自定义类型保护// 1. 定义一个函数 其返回值是一个 类型谓词,即 parameterName is Type 也就是 参数名 is 类型 的形式function isNumber(value: number | string): value is number { // 如果返回 true 则说明 传入的 value 是 is 后面的type return !isNaN(Number(value))}// 2. 定义一个获取数字的函数const getNumber: (value: number | string) =>

Number = (value: number | string,): number = > {/ / if the value of calling isNumber is true, value is a number, so the number is returned to if (isNumber (value)) {return value} / / 3. Call to get the final value const getValue: (arr: (number | string) []) = > number = (arr: (number | string) [],): number = > {for (let I = 0; I)

< arr.length; i++) { // 如果返回数字,转换为 boolean 值为 true if (getNumber(arr[i]) || getNumber(arr[i]) === 0) { return getNumber(arr[i]) } }} 定义第二个函数的原因是在数组中直接使用i作为返回值还是有问题的,所以定义一个函数过渡一下。 3.2typeof 类型保护 JavaScript 中的typeof关键字可以判断当前类型,但是仅仅只能判断number、string、boolean和symbol四种类型。 在这个需求中就足够了,接下来我们看看如何通过typeof来实现类型保护。 示例代码如下: // 1. 定义一个获取数字的函数const getNumber: (value: number | string) =>

Number = (value: number | string,): number = > {/ / determines whether the current value is a string, and if it returns the current value if (typeof value = 'number') {return value}} / / 2. Call to get the final value const getValue: (arr: (number | string) []) = > number = (arr: (number | string) [],): number = > {for (let I = 0; I)

< arr.length; i++) { // 如果返回数字,转换为 boolean 值为 true if (getNumber(arr[i]) || getNumber(arr[i]) === 0) { return getNumber(arr[i]) } }}3.3instanceof类型保护 instanceof操作符也是JavaScript中提供的原生操作符,它用来判断一个实例是不是某个构造函数创建的,或者是不是使用ES6语法的某个类创建的。在TypeScript中也可以通过instanceof操作符来实现类型保护, 示例代码如下: /** * 由于 instanceof 仅仅支持引用类型,不支持原始类型,所以说这里需要进行一下改动,将数组修改为如下: */const arr2: (Number | String)[] = [new String('彼岸繁華'), new Number(10)]// 1. 定义一个获取数字的函数const getNumber: (value) =>

Number = (value): number = > {/ / determine whether the current value is of Number type, and convert the current value to a string and return if (value instanceof Number) {return Number (value)}} / / 2. Call to get the final value const getValue: (arr: (Number | String) []) = > number = (arr: (Number | String) [],): number = > {for (let I = 0; I < arr.length; inumbers +) {/ / if a number is returned, convert the boolean value to true if (getNumber (arr [I]) | | getNumber (arr [I]) = = 0) {return getNumber (arr [I])}}

There are two points to pay attention to when using instanceof:

It only applies to any reference type, and the original type is not supported.

Whether the prototype chain of the former contains the prototype object of the latter.

This is the end of "how to understand TypeScript Joint types, Cross types and Type Protection". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report