In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "what are the entry knowledge points of TypeScript". In the daily operation, I believe that many people have doubts about the entry knowledge points of TypeScript. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "what are the entry knowledge points of TypeScript?" Next, please follow the editor to study!
Preface
What is ts? Ts is actually an abbreviation of TypeScript, just like JavaScript is abbreviated as js. The official explanation is that ts is a superset of js. In fact, js code is essentially compiled by ts, such as writing a js code [xss_clean] (). The above prompt is ts, as shown in the figure:
What is written in the system is ts code, so ts is a superset of js and a language that adds extended functions to js. There used to be a language called as, but this language is no longer available. It is actually flash. But if our development needs to improve js, there must be such a thing, so Microsoft developed ts with the syntax of as, that is to say, the syntax of as and ts is basically the same, but ts was developed by Microsoft, and then promoted well. Now, as our programming becomes more and more popular, ts is used more and more, including when looking for a job, if your salary is more than 12k Basically, they will ask you if you can ts. Today's programming uses ts in many cases, because it can add extended functions to js.
For example: can carry out a variety of modular development, such as the AMD,CMD development mentioned earlier, the modular specification of CommonJS,es6. Suppose you are developing on the client side, is there a development scenario that can use either AMD or CMD,CommonJS,es6
The answer is no, because CommonJS can only be used in nodejs, the modular development of es6 can only be used in the server, they all have their own limitations.
But in ts, you can use whatever you want, and it supports the whole scenario. Ts is more like the back end, and its syntax is most similar to java. What are the advantages of this? We all know that js is a weakly typed language, for example, a variable first defines a numeric type, and then re-assigns a string type, so the type of this variable is changed, and this kind of weakly typed development has a certain security risk to the project.
For example, if you use this variable to do other things, it may become other types of data, so there is a security risk for developers, so there must be ts to regulate js development and eliminate this security risk. This is why when ts back-end languages such as java and # c define variables, they need to declare what the type of these variables is. Once the type of this variable is defined, Later modification of the type is not allowed, and with such specification constraints, development is more secure.
Ts now uses a wide range of scenarios: js hints (the editor has built-in ts for canonical syntax), and the mainstream framework vue,react also uses ts when writing frameworks at the underlying level.
Having said that, let's directly introduce ts, that is, TypeScript.
Introduction to TypeScript
Ts is an extension language that adds features to js.
TypeScript is an open source programming language developed by Microsoft.
TypeScript is a superset of JavaScript and follows the latest es6 and es5 specifications. TypeScript extends the syntax of JavaScript.
TypeScript is more like object-oriented languages such as back-end java and C #, which allows js to develop large enterprise projects.
Google is also strongly supporting the promotion of TypeScript, and Google's angular2.x+ is based on TypeScript syntax.
The latest vue and React can also be integrated with TypeScript.
TypeScript syntax is used in the construction of Nestjs and midway in nodeJs mine.
The features that can be added to js are
Type annotation and compile-time type checking
Type inference
Type erase
Interface
Enumerate
Mixin
Generic programming
Namespace
Tuple
Await
Class
Module
Arrow syntax for lambda function
Optional parameters and default parameters
Js is a weakly typed language, but ts is strongly typed and the syntax is very similar, but ts is the syntax of extended js. Ts provides static type checking when compiling js through type annotations.
Compile
Ts cannot be run directly, so it can only be compiled and run as js. Similar to sass, it is used to compile css and cannot be run directly.
Compilation tool-typescript
Check whether ts has been installed at any location in the world
Tsc-version
Npm install-g typescript
Check if the installation is successful:
Tsc-v
The suffix of the ts file is ts, and the compile command:
Tsc compiled file
A js file with the same name is generated in the same directory of the compiled file.
Generate a file for the custom name path:
Tsc compiled file-- outFile compiled file path
Initialization command:
Tsc-init
After the initialization command is executed, a tsconfig.json file is generated, as follows:
Common configuration items are described as follows:
Represents the js version of ts to be converted
"target": "es5"
If ts is written as a module, what kind of modular specification is used? the default is commonJS.
"module": "amd"
Configure the output directory, which can be set by yourself
OutDir:. / "
Once the above configuration items are configured, executing the monitoring command compiles automatically:
Tsc-w
When using the amd specification, you need to copy the require.js file to the project root, and you need an exit file:
Compile ts to js and automatically generate the target js file
Tsc target js file
Ts Foundation Typ
You need to specify a type when defining a variable, and once the type is defined, you can't change its type-strong type.
Numeric let decLiteral: number = 6; / / decimal let hexLiteral: number = 0xf00d; / / hexadecimal let binaryLiteral: number = 0b1010; / / binary let octalLiteral: number = 0o744; / / octal let num: Number = 5; / / at this point uppercase Number types can be assigned to numeric object types num = new Number (10); Boolean let isDone: boolean = false;let bool: Boolean = true; / / initials can be assigned to object types
Boolean can only be assigned two values of this type: true/false
Var bool: boolean = true var bool: boolean = new Boolean (true)
In addition to the two literal values above, Boolean can also use the constructor method.
Var bool: Boolean = false;var bool: Boolean = new Boolean (true) string var str: string = 'asdfasdf';var str1: String = new String (' 43563456') array
An array written by ts, in which the data must be of the same type, but the length is not specified.
The value type of all data in the array must be a number
Var arr: number [] = [1jimi 2jue 3]; var arr: Array = ['axiajiaoyuanb']
Declare a two-dimensional array
Var arr: number [] var brr: number [] [] = [[1rect 2je 3], [4pr 5rect 6]]; tuple Tuple
Tuples in ts represent collections of different types of data, usually of fixed length, and you can also use subscripts to access elements and assign values to elements
You can put different types of data in tuples.
The tuple is defined with a fixed length.
Var x: [string,number] = ['axiomain 2]; console.log (x); console.log (x [0])
Error
X [2] = 20
Length cannot be added.
Let x: [string, number]; x = ['hello', 10]; x [2] =' world'; / / cannot add length
You can give the element push a value, which must be of type string or number. Other types are not allowed.
X.push ('aaaa')
Error
X.push (true) / / error
When assigning a value to a subscript that does not exist in a tuple, the union type is used:
X [3] = 'world'; / / OK, string can be assigned to (string | number) type x6] = true;// Error, Boolean is not (string | number) type enumeration
The enumeration in ts is equivalent to defining a variable type. This type has a fixed range of values. The default value starts at 0, increases backward, and uses the specified key in exchange for the value. If a variable uses this type, its value must be selected from this type and cannot be assigned at will:
Enumeration-values in the specified collection must be used
The enumeration type actually gives some names to the number, so that we can get the corresponding number through this name.
By default, the value for the first name is 0, incremented backward in turn
Enum Color {Red,Green,Blue}; var c: Color = Color.Blue; / / 2
If one of the names is assigned a value, the value corresponding to his subsequent name is incremented back according to the value here.
Enum Color {Red,Green = 5 var Blue}; var c: Color = Color.Blue; / / 6
Each value can be specified
Enum Color {Red=3,Green = 4Blueprints 2}; var c: Color = Color.Blue; / / 2
You can specify values that are not numeric
Enum Color {Red=' male', Green = 'female', Blue=' neither male nor female'}; var c: Color = Color.Blue; / / neither male nor female
Get the corresponding name from the number of the corresponding value-the name is a string type
Enum Color {Red,Green=5,Blue}; var c: string = Color [6] / / Blue
If we specify that the value is non-numeric, we cannot use this slut.
Enum Color {Red='red',Green = 'green',Blue='blue'}; var c: string = Color [' red']; / / the value in this place must be a number before Any
Any type, which represents weak type, that is, when we define a variable, we can't determine the type of variable value, and we love and hate this type.
Use:
Var a:any = 20var b:any = 'asdfasdf'var c:any = [1JI 2 Jing 3]
Note: originally we use ts to write code in order to restrict types and reduce security risks, but if we use the any type, it will be the same as writing js directly, losing its meaning, so try not to use it unless you have to.
Void
This type is generally used to specify that the return result is void when the result is returned without using return after the function is executed.
Do not use it when declaring a variable-when the function has no return value, the return type is specified as void
Function fn (a console.log number): void {number (apleb);} Undefined
This type is mainly used for parameters and return values, but it is meaningless for variables, because when a variable is specified as a undefined type, it can only be a undefined type, the usage in the function:
Function fn (num:number | undefined): number | undefined {return num;}
Undefined-No type defined
Var a:undefined = undefined
You don't use undefined to define variables because defining them is useless.
It is usually used in the parameters of a function
You want the parameter an of the fn function to be optional
Function fn (a:number | undefined): void {console.log (a);} fn (undefined)
The function is optional
After the parameter name, before the colon of the type? Indicates that this parameter is optional
Undefined is usually used in the function return value. If undefined is returned, you need to specify the undefined type in the return value.
Function fn (a?:number): number | undefined {return a;} fn () Null
Null type-null-this data is about to be destroyed
Usually used when defining complex data types and later when you need to assign a value to null
Var a:number | null = 10
Use variable a to calculate-complete
Let memory recycle this variable
A = nullNever
The never type represents a type of value that never exists, for example, an error thrown in a function that has an endless loop that can never be returned.
Function fn (): never {throw new Error ('error')} function fn (): never {return fn ()} fn () Object
Object type:
Var obj: object = {name: "Zhang San"}
Incorrect writing-objects are not allowed to add key-value pairs by default
Obj.name = 'Zhang San'; type assertion
If there is more possibility of a type type after a piece of code is executed, you need to assume what type it is-this operation is called assertion.
If the result of an expression is likely to be of multiple types, you eventually need to affirm one of them
Var abcd: any = [1, 2, 3, 4, 5]
Assert that the abcd variable is an array
(abcd as [string,number]) .push (6) (abcd as string) + = 'ddd' function declaration
In ts, function definitions have more type definitions of parameter types and return values than in js:
Definition of function, type declaration of parameter, type declaration of return value
Function fn: number {/ / console.log (avelb); return aquib} var res = fn (1mai 2)
Parameter default value
Function fn (av number.bjv numbering 3): number {return aquib} var res = fn (1)
However, when indicating that the parameter is optional, it is written slightly differently:
The parameter is optional -? It means that it is optional.
Function fn: number {if (! b) {return axiom 5} return aquib} / / var res = fn (1) var res = fn (1Pol 3)
Parameters with default values must be placed at the end of all parameters
Optional parameters, which must be placed at the end of all parameters
The expansion operator and the merge operator can also be used in ts, but pay attention to the type setting of the variables after the operator.
Calculate the sum of indefinite arguments
Function sum (. Arr:Array) {var sum = 0; for (var ilistenerList [type] .splice (index,1);} dispathEvent (evt:MyEvent): boolean {var list:Function [] = this.listenerList [evt.type]; if (! list) return false; evt.myTarget = this; evt.target = this; for (var i:number=0) I
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.