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 parse TypeScript basic types

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

Share

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

How to analyze the basic types of TypeScript, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

The static types of TS can be artificially divided into two categories:

Basic types: like Boolean (boolean), number (number), string (string), Any (any type), Void (untyped), Null, Undefined, Never (no type)

Object types: like arrays, functions, objects, enumerations, tuples.

1. Basic type

The type definition of TS is mainly defined in the way demonstrated in the following sample code:

(function () {/ * * in TS, you can define the data type by let variable name: data type = variable value worthwhile (type annotation) * or you can not specify the data type at the time of definition. TS itself will infer that the data type * / / Boolean let boo: boolean = false / / assign a non-Boolean value will throw an exception / / numeric type let num: number = 100 / / string let str: string = 'string' / / use single or double quotation marks to locate str = `template string `/ / define / / Any class using template string Type-> indicates that the type can be a dynamic type This type is removed at compile time let AnyType: any = 123 AnyType = true / / repeat assignment does not throw an exception / / Void type-> is usually used for function types that do not return values function demo (): void {console.log ('test void type')} demo () / / there are two more special types, that is, null and undefined / / are subtypes of all types That is to say, you can assign these two types to number, string and other types let u: undefined = undefined num = u / / assign variables of type number to undefined let n: null = null boo = n / / assign variables of type boolean to null}) ()

The basic type is relatively simple, especially similar to JavaScript. Simply speaking, it has one more type definition than JavaScript.

There is also a Never type in TS. This type represents those worthwhile types that will never exist.

For example, the never type is the return value type of a function expression or arrow function expression that always throws an exception or has no return value at all.

two。 Object Typ

2.1 Array

Arrays in TS are different from arrays in JS. Using arrays in TS can not only define a variable as an array, but also locate types in the array.

The sample code is as follows:

(function () {/ / define an array type let arr1: number [] = [1,2,3] console.log (arr1) / / define an array that can be a Boolean value of a numeric string let arr2: (number | string | boolean) [] = ['1numbers,' 2numbers, true] console.log (arr2) / / define an array of any type let arr3 = [1 Console.log (arr3) / / defines an array of object types ['1percent,' 2percent, true], true] There must be two properties, name and age, const objectArray: {name: string in the object Age: number} [] = [{name: 'bowl week', age: 18},] / or declare / / define a type alias through type type User = {name: string; age: number} const objectArr: User [] = [{name: one bowl week, age: 18}]}) () 2.2 tuples

Tuple types allow you to represent an array of known number and type of elements, and each element does not have to be of the same type.

The sample code is as follows:

(function () {/ / define a tuple let tuple whose values are string and number respectively: [string, number] = ['123, 123] console.log (tuple) / assign tuple [0] =' string' console.log (tuple) / / ['string'] by index 123] / / assign other types / / tuple [0] = true / / console.log (tuple) / / throw exception}) ()

The main function of a tuple is to constrain each item in the array and the length of the array.

Tuples and arrays can be nested, and the syntax is as follows:

/ / nested let tuples of tuples and arrays: [string, number] [] = [['123, 123], [' 456, 456],]

In the above code, [string, number] represents a tuple, followed by [], which represents an array of tuples.

2.3 object

An object can contain all of the above types, and the sample code is as follows:

(function () {/ / defines an object that contains two attributes, MyName and age, where MyName is the string type age is the number type let obj: {MyName: string age: number} / / assignment of the object If you do not assign to the type specified above, an exception will be thrown obj = {MyName: 'bowl week', age: 18,} console.log (obj) / / {MyName: 'bowl week', age: 18}}) ()

We don't need to label types everywhere in TS, because type inference can help us get its functionality without writing extra code. But if you want to make your code more readable, you can write each type.

3. Type inference

Sometimes in TypeScript and you need to specify a type explicitly, the compiler automatically infers the appropriate type, such as the following code:

; (function () {let myName = 'bowl week' myName = true / / error: type "boolean" cannot be assigned to type "string"}) ()

When we define a myName variable, we don't specify its data type, we just assign it a string value, but the compiler will throw an exception if we re-assign this value to a value of a non-string type.

This is the simplest type inference in TypeScript, extrapolating the data type of a variable from the value on the right.

3.1 Type inference in type association

What is type federation? please refer to: Union type, cross type and type protection.

If a variable may have values of multiple types, TypeScript will merge the types to form a federated type

The sample code is as follows:

Let arr = [1,'2'] / / define an array containing strings and numbers / / reassign the array defined above / / arr = [true False] / / error cannot assign type "boolean" to type "string | number" / / there is also the following example: let val = arr.length = = 0? 0: 'array length is not 0 inch / val = false / / error cannot assign type "boolean" to type "string | number" 3.2 context type

The previous examples may infer the type on the left side of = based on the value on the right side of =. The type of context to be introduced now is different from the previous type inference, and the compiler infers the type of the variable based on the context in which the current variable is located.

The sample code is as follows:

(function () {/ / define an interface interface Person {name: string age: number} / / define an array let arr: Person [] = [{name: 'one bowl week, age: 18}] / / traverse the defined array arr.forEach (item = > {/ / depending on the current environment The compiler automatically infers that item is of type hobby and does not have the hobby attribute console.log (item.hobby) / / there is no attribute "hobby"} on type "Person")}) ()

In the above code, we first define an interface for Person, and then use this interface to define an array. When traversing the array, the compiler infers that item is of type Person, so the compiler throws an exception.

If we add type comments to the parameters of the function expression, the context type will be ignored and the error will not be reported.

The sample code is as follows:

/ / if the type information is specified in the context, the context will be ignored. Arr.forEach ((item: any) = > {/ / according to the current environment, the compiler automatically infers that item is of type hobby and does not have the hobby attribute console.log (item.hobby) / / the attribute "hobby"} does not exist on the type "Person") 4. Type assertion

The so-called type assertion is that you tell TS that the worthwhile data type is something, and you don't need to check it.

In this way, it will not affect it when it is running, but only when it is compiled.

The sample code is as follows:

Let SomeValue: any = 'this is a string'// syntax-let StrLength2: number = (SomeValue). Length// syntax two as syntax let StrLength3: number = (SomeValue as string) .length

It is worth noting that when using JSX in TS, only the second syntax is supported.

After reading the above, have you mastered how to parse the basic types of TypeScript? If you want to learn more skills or 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