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 use TypeScript type annotations

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

Share

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

Editor to share with you how to use TypeScript type notes, I hope you will learn something after reading this article, let's discuss it together!

Type annotation

TypeScript provides many data types, which restrict variables by type, which is called type annotation. After using type annotation, you can't change the type of variable at will.

The following code defines a variable of type string, and if you change it to a numeric type, the code compilation phase will directly report an error, prompting "Type 'number' is not assignable to type' string'".

This ensures that the data type of the variable is fixed, then the method it can use is also determined, and there is no occurrence that the variable is originally a string and the toUpperCase method is called, and then the error is reported directly by calling toUpperCase after inadvertently changing it to a numeric type in an untested scenario.

Type derivation

When a variable does not write a data type, "type derivation" is carried out within ts, and the data type of the variable is determined by the context assignment statement, so when the type annotation is simple and it can derive the type accurately and automatically, not writing the type annotation has no effect on the code quality.

Data types common to TS and JS

TypeScript contains the data types owned by JavaScript, string, number, symbol, array, boolean, undefined, null, object.

Among them, when defining array, you need to add the type of each data in the array, whether it is a string, a number or an object, which makes it impossible to write multiple data types in the array. If you need to write multiple data types, you can simply not add type annotations and automatically carry out [type derivation].

Let str: string = "string"; let num: number = 0 sym sym: symbol = Symbol ("sym"); let arr1: string [] = ['alice',' kiki', 'heidi'] let arr2: object [] = [{name:' alice'}] let arr3: number [] = [1,2,3] let flag: boolean = false;let und: undefined = undefined;let nu: null = null;let user = {name: "alice"}

The object user above is also unannotated because if it is defined as an object type, you cannot get and modify properties on the user object.

This is because user is an object type, but there is no name attribute on the object type, so the compilation phase will report an error directly, so the object can be inferred automatically without type annotations.

Data types unique to TS

In addition, TypeScirpt also adds a lot of data types that JavaScript does not have.

Any

Any is a "one-size-fits-all" data type, representing the "arbitrary" data type. When the type of the variable is uncertain and may change, it can be defined as any. At this time, the data type of the variable can be changed at will, which will actually bring some security risks.

For example, the following code uses strings as functions and undefined uses numeric methods. Because it is an any type, the type may be changed to strings, numbers, and Boolean values, so such code will not be detected by ts, but it will definitely report an error at run time.

Let message: any = "message"; message (); message = 0 World message = undefined;message.toFixed ()

Unknown

When the type of a variable is temporarily uncertain, you can use unknown to restrict its type.

Let flag = truelet result: unknown;if (flag) {result = 'Hello World'} else {result = 888}

It is similar to any, except that unknown cannot be assigned to variables other than any and unknown, so that the value of unknown cannot be misused elsewhere.

Void

When a function does not return a value, it actually returns undefined,void, which is usually used to indicate that the return value of the function is undefined or null.

The following forms are all fine

Function add (): void {} function sub (): void {return undefined} function mul (): void {return null}

Compilation will report an error when there is a return value.

Never

Never represents a type that will never exist and can be used if the function is a dead loop or if an exception is thrown.

Function foo (): never {while (true) {}} function catchError (): never {throw new Error ("error");}

When we encapsulate the tool function, the specified function input parameter is the string type, but the number type may be added later in the development process of others. In order to avoid forgetting to deal with the data of this type during maintenance, you can assign the input parameter to the variable of never type, so that the compiler fails to prevent the developer from logical omission.

Tuple

Tuple means tuple, which is similar to an array, but there are still the following differences between tuples and arrays.

The element data types in the array are recommended to be consistent, and when the data types are inconsistent, consider putting them into tuples or objects.

Each element in a tuple has its own characteristics, which can be obtained by index values.

/ / Array const array: string [] = ["alice", "kiki"]; / / tuple const tuple: [string, number] = ["alice", 20]; function parameters and return values

When declaring a function, add a type comment after each parameter of the function to declare the type of parameter accepted by the function and limit the type and number of parameters.

A type annotation defined after the list of functions that restricts the type of value returned by the function.

/ / restricted entry type function foo (message: string, no: number) {} / / restricted return value function baz (message: string): string {return "string";}

When the type / number of input parameters does not meet the annotation requirements, the compilation will be marked red to remind you.

Object types, optional types, and union types can also be used to specify function input parameters.

Object type, defining the data type of each parameter in the object

Optional type, use? Means that the parameter is not required and must be written after the required type

Union type, represented by |, A | B means that the input parameter type is any one of An and B.

Function getPoint (point: {x: number; y: number; zoning: number}) {} getPoint ({x: 10, y: 20}); getPoint ({x: 10, y: 20, z: 30}); function printId (id: string | number) {} printId (1); printId ("alice"); function foo (message?: string) {} foo ("message"); foo ()

When the specified type is long, you can use the type keyword to define the type alias

At the same time, if the parameter type is [optional type], it can be understood that the parameter type is the same as the joint type of undefined. The input parameters of the following two parameters are essentially the same.

Function foo (message?: string) {} foo ("message"); foo (); function baz (message: string | undefined) {} baz ("message"); baz (undefined); Type assertion

Sometimes TypeScirpt gets a wide range of types, so you can use type assertions to define specific data types through the keyword as.

For example, two classes are defined below. Student inherits from the Person class and has its own studying method. Define the sayHello method, which requires that the input parameter type is Person. In this case, create an instance object of Student, student, and call the sayHello method to input student.

Class Person {} class Student extends Person {studying () {}} function sayHello (p: Person) {} const student = new Student () sayHello (student)

There is no problem with the above code when compiling, but if you want to call the studying of the Student instance object in the sayHello method, it is not allowed, because although the passed parameter is the instance object of Student, it can only be detected as Person in TypeScript, and there is no studying method on Person.

To call correctly, you need to use type assertions to specify the actual type of the input parameter

Function sayHello (p: Person) {(p as Student) .studying ()} non-empty type assertion

Yes! Symbol to prevent code that cannot be compiled from being red-alerted, but an error is still thrown if there is a problem with the run-time code.

Literal quantity

The data type of a variable defined by const is literal, and the value in the literal quantity is the content of the variable assignment.

The literal quantity type can be used to specify the selection range of variables. For example, the direction of flex layout can choose row or colums.

Type DirectionType = "row" | "colums"; let direction: DirectionType = "row"; direction = "colums"

A red reminder is given when a variable is assigned to something that is not included in its type annotation.

Type reduction

Type reduction means that when the range of variable data types is relatively large, we can judge the types of variables by means of if, switch, in, typeof, instanceof and so on, in order to achieve more accurate operation.

For example, the parameter types of a function may be string and number, and getting the length property directly will cause an error. Because only variables of type string can get length, but it does not exist on the type of number, the type of input parameter can be determined by typeof at this time, which is also called "type protection".

After reading this article, I believe you have some understanding of "how to use TypeScript type annotations". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

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