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

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

Share

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

Today, I would like to talk to you about how to understand TypeScript. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something from this article.

Preface

TypeScript is a strongly typed language, so it has stronger language specification constraints than JavaScript, which can make our code more readable. At the same time, error checking can be carried out in the compilation process, which improves the development efficiency of our code.

1. What is Typescript?

TypeScript is not a new programming language, it is a superset of Javscript, which adds language constraints to the JavaScript language: optional static types and class-based object-oriented programming. In fact, static type checking is added, and constraints allow us to reduce the writing of error code in the development process.

The relationship between TypeScript and JavaScript is as follows:

The difference between TypeScript and JavaScript:

two。 Two minutes to get started with TS development

"if workers want to do what they do, they must sharpen their tools", which means to make all preparations before doing things. Similarly, if we want to learn TS development, we must first install the locale and editor tools.

Install TypeScript

There are two ways to get the TypeSscript tool:

Install via NPM

Install the TypeScript plug-in for VScode

(1) NPM installation:

Npm install-g typescript

(2) verify TS installation

Tsc-v # Version 4.2.4

(3) build a TS file to build a TS file test.ts in the editor:

Function addNum (num1:num,num2:num) {return num1 + num2;} console.log (addNum (1pm 2)); / / 3

(4) compile the code:

Tsc test.ts

Compile the JS code:

"use strict"; function addNum (num1, num2) {return num1 + num2;} console.log (addNum (1,2)); 3. Basic type

3.1 Boolean Typ

There are only two values: true and false.

Let isTrue: boolean = true;3.2 Number type

All numbers are floating-point and support binary, octal, decimal, and hexadecimal literals.

/ / numeric type, all digits are floating-point let decLiteral: number = 10; let hexLiteral: number = 0xf00dent3.3 String type

TS can use double quotation marks (") or single quotation marks (') to represent strings.

/ / string, indicating the text data type let username: string = "yichuan"; let like: string = `$ {yichuan} + FE`

3.4 Array Typ

Array operations can be declared in two ways:

You can append [] to the element type to represent an array of elements of that type.

Use array generics, Array.

Let list: number [] = [1,2,3]; let list: Array = [1,2,3]; 3.5 Tuple type

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.

/ / tuple let tuple: [string,number]; tuple = ["wenbo", 1]

TS tuples are pretty much the same as arrays, except that the element types in the array must be the same, while tuples can store different types of elements. You can even say that a tuple is an array of type any.

3.6 Enum Typ

The enum type is a supplement to the JavaScript standard data type. One of the conveniences provided by an enumerated type is that you can get its name by enumerating it.

/ / enumeration / / by default, the element number of an enumeration starts at 0, or it can be numbered manually. Enum Color {Red, Green, Blue}; let c:Color = Color.Red;3.7 Any type

Any stands for any type. Sometimes we want to specify a type for variables that are not yet aware of the type during the programming phase.

/ / Any let notSure:any = 100.002; notSure.toFixed (); let list3:any [] = ["zhaoshun", "male", 12]

In fact, the any type is the top-level type of the type system, because any type is attributed to the any type, which is not very free. Freedom has gone too far, and an inappropriate metaphor is that JS is a TS of type any, allowing various operations on values of type any without compiling checks.

3.8 Void Typ

The void type, which means that there is no type. When a function does not return a value, you will usually see that the return type is void.

Declaring a variable of type void is not very useful, because you can only assign null and undefined to it.

Function showName (): void {console.log ("your name is wenbo");} / / declare a variable of type void let unusable: void = undefined;3.9 Null and Undefined

In TypeScript, undefined and null each have their own types called undefined and null. By default, null and undefined are subtypes of all types, and you can assign null and undefined to variables of type number.

Let u: undefined = undefined; let n: null = null

However, when the-- strictNullChecks flag is specified, null and undefined can only be assigned to void and to each.

3.10 Object

Object represents a non-primitive data type (other than number,string,boolean,symbol,null or undefined).

Declare function create (o: object | null): void; create ({prop: 0}); / / OK create (null); / / OK create (42); / / Error create ("string"); / / Error create (false); / / Error create (undefined); / / Error3.11 Never

The never type represents the types of values that never exist.

The never type is a subtype of any type and can be assigned to any type; however, no type is a subtype of never or can be assigned to a never type (except never itself). Even any cannot be assigned to never.

/ / the function that returns never must have an unreachable destination function error (message: string): never {throw new Error (message);} / / the inferred return value type is never function fail () {return error ("Something failed");} / / the function that returns never must have an unreachable destination function infiniteLoop (): never {while (true) {}} 3.12 Unknown type

Any type can be classified as a unknow type, so unknow is also the top-level type in the ts type.

Let value: unknown; value = true; / / OK value = 18; / / OK value = "yichuan"; / / OK value = []; / / OK value = {}; / / OK value = Math.random; / / OK value = null; / / OK value = undefined; / / OK value = new TypeError () / / OK value = Symbol ("type"); / / OK

When we see that all the assignments are correct for value variables, we will feel that they are no different from any. Is that really the case? When we assign other types, there is an unexpected problem and find that the unknow type can only be assigned to the any type and the unknow type itself, which is the difference from any.

Let value: unknown; let value1: unknown = value; / / OK let value2: any = value; / / OK let value3: boolean = value; / / Error let value4: number = value; / / Error let value5: string = value; / / Error let value6: object = value; / / Error let value7: any [] = value; / / Error let value8: Function = value; / / Error

So the result: only containers that can hold values of any type can save values of type unknown.

It is worth noting that TS does not allow us to do anything on values of type unknow, we must first perform type checking and then determine the range of values to be used. So how to narrow the range of unknown values?

Quite simply, our old friends typeof, instanceof operators and custom type protection functions all contribute to TypeScript's control flow-based type analysis by using techniques that narrow the scope of types.

For example, by branching if statements

Function stringifyForLogging (value: unknown): string {if (typeof value = "function") {const functionName = value.name | | "(anonymous)"; return `[function ${functionName}]`;} if (value instanceof Date) {return value.toISOString ();} return String (value);}

Narrow the scope of unknown types by using custom type protection functions.

Function isNumberArray (value: unknown): value is number [] {return (Array.isArray (value) & & value.every (element = > typeof element = "number"));} const unknownValue: unknown = [15,23,8,4,42,16]; if (isNumberArray (unknownValue)) {const max = Math.max (.unknownValue); console.log (max);}

Although unknownValue has been classified as unknown, notice how it still gets the number [] type under the if branch.

After reading the above, do you have any further understanding of how to understand TypeScript? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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