preface

Hello, everyone, I am eight character nickname, after more than a year, I finally sent an article, what? I’m so lazy? I am really lazy 😂😂😂

So how did I come up with the idea of Posting an article after all this time?

Recently, my leader asked me to unify some front-end technology stacks, and TypeScript is the first one to be unified. Yes, our company will use TypeScript for front-end development in the future. As for the benefits of TypeScript, we can find them at any time.

So I started writing this basic tutorial in my spare time on Tuesday (working overtime? Overwork is impossible overwork, interface all one’s life impossible overwork, did not have overwork fee again, did not have overwork welfare again, can come off work early ability maintain of life this 😑😑), since write, be about to send out to help (water) help (wave) big (classics) home (check).

Disclaimer: ✨ This series of articles as the basis of the tutorial, does not involve too deep things, more suitable for beginners to see, if you already know the students, after reading this paragraph can run away 😋.

The preparatory work

In front of a lot of nonsense, so, how to use such a good and popular technology

The installation

NPM install -g TypeScript

Write code in the editor once installed (no extra configuration, popular editors support TypeScript well)

Start your first TypeScript program, Hello Word

Create a new hellowtypescript. ts file in webStrom and type:

console.log('hellow TypeScript')
Copy the code

Command line input: TSC hellowtypescript.ts

When compiled, you get the hellowtypescript.js file, which you can run using Node or in a web browser

Underlying data types

Boolean type (Boolean)

A Boolean type is as simple as adding a type to its definition and assigning it:

let isClose:boolean=true
Copy the code

Or call the Boolean method:

let isClose:boolean= Boolean(true)
Copy the code

There are only two allowed values: true/false, if not, the compiler will report an error:

let isClose:boolean=2
Copy the code

Error as follows:

Type '2' is not assignable to type 'boolean'.

Note that the Boolean constructor returns a Boolean object, so we cannot assign to Boolean data:

let isClose:boolean=new Boolean(true)//Type 'Boolean' is not assignable to type 'boolean'.
Copy the code

Numeric type (number)

Numeric types are defined by number:

Let num: number = 6 let num2: number = number (2) Type 'number' is not assignable to Type 'number'. Let hexNum: Number = 0xf00D // Hexadecimal let binaryNum: number = 0b1010 // Binary let octalNum: number = 0o744// octal let notANumber: number = NaN let infinityNumber: number = InfinityCopy the code

String type (string)

Use string to define characters:

let firendNum:number=20 let myName:string='jepson' let lastName:string=String('smith') let addres:string=new String (' Smith ') / / error: // Equivalent to lastName+myName+' has '+firendNum+' friends' let Message = ` ${myName}, ${lastName} from the ${firendNum} friends `Copy the code

Null, and undefined

Null and undefined are subtypes of all types in TypeScript, and all other types can be assigned null and undefined:

let u:undefined=undefined
let n:null=null
let num:number=undefined
let str:string=null
Copy the code

Why not, you may ask, in a Vue project?

The strictNullChecks flag is used by default in the Vue project, which avoids many errors, so if you want to be able to assign null or undefined, you’d better explicitly declare:

let name:string|null|undefined=null
Copy the code

Symbol (always unique value)

Symbol is a new primitive of ES6, which means an immutable and unique value. If you don’t already know this type, check out the Symbol section of ECMAScript6 by Yifeng Nguyen. Represented in TypeScript as symbol:

let globalKey:symbol=Symbol()
let globalKey2:symbol=Symbol()
console.log(globalKey===globalKey2)//false
Copy the code

Void

Void denotes a null value and can only be assigned to null/undefined(a subtype of any type). This may not be useful when used in variables, but when used in functions to indicate that no value is returned: void void denotes a null value and can only be assigned to null/undefined(a subtype of any type).

let myFirstName:void=undefined let myLastName:void=null function fn1():void { return null } function fn2():void { return  undefined } function fn3():void { console.log('this is fn3') }Copy the code

Angel or devil?

Any Indicates any type, such as third-party libraries, uncertain data returned from the backend (try to ensure that the data returned from the backend is certain), and dynamic content:

let anyValue:any=true
anyValue=20
anyValue='anyValue'
anyValue=Symbol()
anyValue=null
anyValue=undefined
anyValue=new Error('anyvalue')
anyValue=['anyValue']
Copy the code

The any type in TypeScript was once ridiculed by a famous developer (I can’t remember what it was, but he said this) :

Any is the biggest TypeScript Bug

** Note: the editor and compiler will not check when you specify any, which may be a convenience, but on the other hand, not checking means that many related errors will not be reported in the editor or at compile time, so avoid using any in projects

function

Functions are very important in Javascript because all behavior is performed through functions. In the Book The Functional Programming Guide:

Functions are first-class citizens of Javascript

TypeScript functions that take both input and output into account:

Function add(num1:number,num2:number):number {return num1+num2} const function add(num1:number,num2:number) Reduce = (num1: number, num2: number) : number = > num1 - num2 console. The log (add (1, 1)) / / 2. The console log (reduce (1, 1)) / / 0Copy the code

Types in functions

As in the code above, the function needs to specify the types of input and output:

  • An error will be reported if there are too few input parameters, too many input parameters, or the parameter type does not match
  • If the input type is not specified, the default is any (any is not recommended, so errors will be reported in the Vue project)
  • If the output type is not specified, the default value is void, indicating that no result is returned. If there is a return, TypeScript automatically inferences the type based on the returned data
Function runAway() {console.log(' this is a black factory ')}Copy the code

The above code is equivalent to the following code:

Function runAway():void {console.log(' this is a black box ')}Copy the code

Here is an example of an automatic type inference:

Const num:number=add(1,2) function add(num1:number,num2:number) {return num1+num2} const num:number=add(1,2)Copy the code

Optional and default parameters

Optional parameters

For some cases where parameters are not required, you can use optional parameters. : definition, indicating that this parameter is not required:

/** * Analog lunch behavior * @param mianFood * @param mainCourse * @param sideDish * @param soup, @param drinks, @param fruits, @param fruits, function haveLunch(mianFood: string, mainCourse: string,sideDish:string,soup? : string, drinks? : string, fruits? : string) { const foods = Object.keys(arguments).map((key: String) => arguments[key]) console.log(' arguments[key] ') ${food.join (', ')} ')} haveLunch(' rice ', 'pig's trotters ',' lettuce in oyster sauce 'Copy the code

If optional parameters are filled in, they must be filled in order (soup must be filled in if drinks are filled in) :

/** * Analog lunch behavior * @param mianFood * @param mainCourse * @param sideDish * @param soup, @param drinks, @param fruits, @param fruits, function haveLunch(mainFood: string, mainCourse:) string, sideDish: string, soup? : string, drinks? : string, fruits? Const foods = [' mainFood: ${mainFood? MainFood: 'no '}', 'mainFood: ${mainCourse? MainCourse: 'no'} `, ` vice cuisine: ${sideDish? SideDish: 'no'} `, ` soup: ${soup? The soup: 'no'} `, ` beverages: ${the drinks? The drinks: '} ', 'fruit: ${fruits? Fruits: \n${food.join ('\n')} ')} // \n${food.join ('\n')} ')} // \n${food.join ('\n')} ')} Lettuce in Oyster sauce // Soup: Coke (cola is originally a drink) // Beverage: no // fruit: no haveLunch(' rice ', 'pig's trotters stewed with soy beans ',' Lettuce in Oyster sauce ', 'Cola ') // Lunch time, start to eat lunch, today's lunch has: // staple food: rice // main course: Stewed pig's trotters with soybean // Side dish: Lettuce with oyster sauce // Soup: tomato and egg soup // Drink: Coke // Fruit: haveLunch(' rice ',' stewed pig's trotters with soybean ',' lettuce with oyster sauce ',' Tomato and egg soup ',' Cola ')Copy the code

Note that optional parameters cannot be followed by mandatory parameters. Mandatory parameters can only be preceded by 0 or 1 mandatory parameter

/** * Analog lunch behavior * @param mianFood * @param mainCourse * @param sideDish * @param soup, This is a non-mandatory parameter * @param drinks, this is a non-mandatory parameter * @param fruits, this is a non-mandatory parameter */ / error: A required parameter cannot follow an optional parameter. function haveLunch(mainFood: string, mainCourse: string, sideDish: string, soup? : string, drinks: string, fruits? Const foods = [' mainFood: ${mainFood? MainFood: 'no '}', 'mainFood: ${mainCourse? MainCourse: 'no'} `, ` vice cuisine: ${sideDish? SideDish: 'no'} `, ` soup: ${soup? The soup: 'no'} `, ` beverages: ${the drinks? The drinks: 'no'} ` ` fruit: ${fruits? Fruits: 'no'} `,] the console. The log (` lunch time, began to eat lunch, have lunch today: \ n ${foods. Join (' \ n ')} `)}Copy the code

The default parameters

The default parameter is a new feature of ES6. If you are not familiar with this feature, please refer to ruan Yifeng’s introduction to ECMAScript

Use to set default values for items that are not required:

/** * analog lunch behavior * @param mianFood * @param mainCourse * @param sideDish * @param soup, default is none, Optional * @param drinks, default: boiled water, optional * @param fruits, default: none, optional */ function haveLunch(mainFood: String, mainCourse: string, sideDish: string, soup: string=' no ', drinks: string=' white ', fruits: String =' no ') {const foods = [' mainFood: ${mainFood? MainFood: 'no '}', 'mainFood: ${mainCourse? MainCourse: 'no'} `, ` vice cuisine: ${sideDish? SideDish: 'no'} `, ` soup: ${soup? The soup: 'no'} `, ` beverages: ${the drinks? The drinks: '} ', 'fruit: ${fruits? Fruits: \n${food.join ('\n')} ')} // \n${food.join ('\n')} ')} // \n${food.join ('\n')} ')} Lettuce in Oyster sauce // Soup: no // Drink: plain water // Fruit: no haveLunch(' rice ', 'pig's trotters stewed with soy beans ',' Lettuce in Oyster sauce ')Copy the code

The default parameters are different from the optional parameters:

  1. The default parameter has no location limitation. The first parameter can also be set as a default parameter, followed by mandatory parameters
  2. Default parameter if passedundefined,nullDefault values are not replaced, and optional parameters are copied directly; This feature allows you to set a default value for each parameter and pass it in if it is the default valueundefinedornull
// The main course: stewed pig's trotters with soy beans // Side dish: lettuce with oyster sauce // Soup: no (undefined) // Beverage: boiled water (null) // fruit: Watermelon haveLunch(' rice ', 'pig's trotters stewed with soy beans ',' Lettuce in Oyster sauce ',undefined,null,' watermelon ')Copy the code

=> with the arrow function

You must be wondering, is => not the ES6 arrow function, what else is there to say?

In TypeScript type definitions, => is used to represent functions with input types on the left and output types on the right.

In ES6, => represents an arrow function, left argument, right code block

The following example illustrates the difference between TypeScript type definitions and ES6 =>

let add: (num1: number, num2: number) => number
add = (num1, num2) => num1 + num2
Copy the code

Rest parameters (residual parameters)

The REST parameter is a new feature in ES6. For those who don’t know, see Portal: Getting Started with ECMAScript functions

Rest parameters can be typed in TypeScript:

function add(num1:number,num2:number,... numArr:number[]):number { let num=num1+num2 numArr.forEach((n:number)=>{ num+=n }) return num } The console. The log (add (1,1,1,1,1,1)) / / 6Copy the code

Interface (s)

Interfaces are an important concept in object-oriented languages. They are an abstraction of behavior, and that behavior needs to be implemented by classes.

Interfaces in TypeScript are very flexible. They are often used to abstract parts of a class’s behavior and specify object shapes (which properties/methods)

interface User { username:string; password:string; } // const u:User={username: 'admin', password: Type 'number' is not assignable to Type 'string'. Level :1 password: string; level: number; }' is not assignable to type 'User'.} const u2:User={username: 'admin', password: '12345678'}Copy the code

Optional attribute

Interface specifies which attributes the object should have. Sometimes, some attributes of the object are not fixed. In this case, we can define an optional attribute.

interface User { username:string; password:string; level? :number } const u:User={ username: 'admin', password: '12345678' }Copy the code

Read-only property

One application scenario is that you want an object to have its value initialized at creation time and not be able to change its value once initialized. This is where the read-only attribute comes in handy:

interface User { readonly username:string; password:string; level? :number } const u:User={ username: 'admin', password: '12345678', level:1} u.serName ='Admin'// Cannot assign to 'username' because it is a read-only property.Copy the code

Function attributes

So, how do you specify functions in an object?

Using the functionName (… Args :dataType): specifies the form of returnType:

interface User { readonly username:string; password:string; level? :number; upgrade(level:number):number } const u:User={ username: 'admin', password: '12345678', level:1, upgrade(level:number): number { this.level+=level return this.level } } console.log(u.upgrade(2))//3Copy the code

Dynamically indexable properties implement pseudo-arrays

As mentioned earlier, TypeScript interfaces are flexible enough to use dynamic indexable attributes, so we can use this to implement pseudo-array types:

interface PseudoArray{
  [index:number]:number
}

const pseudoArray={
  0:20,
  1:11,
  2:33
}
Copy the code

Or dynamic objects:

const pseudoArray = {
  0: 20,
  1: 11,
  2: 33
}

interface DynamicObject {
  [key: string]: any
}

const dynamicObject = {
  name: 'jepson',
  address: 'anywhere'
}
Copy the code

Interfaces define function types

You can define a type for a function using an interface:

interface Add {
  (num1: number, num2: number): number
}

let add: Add = (num1, num2) => num1 + num2
Copy the code

Inheritance between interfaces

What is inheritance? The following quote is from Wikipedia:

Inheritance is a concept in object-oriented software technology. If A class B “descends” from another class A, that class B is called A “subclass of A”, and calling A “parent class of B” can also be called “A is A superclass of B”. Inheritance allows a subclass to have various attributes and methods of its parent class without having to write the same code again. When the subcategory inherits the parent category, you can redefine some attributes and rewrite some methods, that is, overwrite the original attributes and methods of the parent category, so that it has different functions from the parent category. It is also common to append new properties and methods to subclasses. In normal static object-oriented programming languages, inheritance is static, meaning that the behavior of subclasses is determined at compile time and cannot be extended at run time.

Some programming languages support multiple inheritance, which means that a subclass can have more than one parent class at the same time, such as the C++ programming languages. In some programming languages, such as the Java programming language, where a subclass can only inherit from a parent class, you can implement interfaces to achieve a similar effect to multiple inheritance.

In today’s object-oriented programming techniques, inheritance is not about inheriting the “behavior” of the class, but rather inheriting the “type” of the class, making components of the same type. Another rule mentioned in the design pattern, “Use composition more, use inheritance less,” is also used to deal with the regret that inheritance cannot dynamically extend behavior at run time.

Inheritance in TypeScript is flexible and can be multiple inheritance with extends:

{eat(food: string): void; eat(food: string): void; run(): void; sleep(): void; } /** * Extends Animal {name: string; hair: string; readonly birthday: Date; sex: 'MAN' | 'WOMAN'; // The union type here will be covered in the next article, interest: string; age: number; } /** * Male extends Human {age: number; // ** ** Women are essentially Human and therefore inherit some of the attributes */ Interface Woman extends Human {age: 18; } const epson: Man = {age: 28, birthday: new Date(1992,1,1), hair: Name: 'epson', sex: 'MAN', eat(food: string): Void {the console. The log (` ${this. The name} ${food} `)}, the run () : void {the console. The log (` ${this. The name} started running `)}, sleep () : Void {console.log(' ${this.name} lay down to rest ')}} const marry: Woman = {age: 19,//Type '19' is not assignable to Type '18'. Birthday: new Date(1992,1,1), hair: 'long hair ', interest:' shopping ', name: 'Mary' sex: 'MAN, eat (the food: string) : void {the console. The log (` ${this. The name} ${food} `)}, the run () : Void {console.log(' ${this.name} start running ')}, sleep(): void {console.log(' ${this.name} lie down and rest ')}}Copy the code

An array of

TypeScript defines array types so that there can be no other type in an array than the specified type. Errors are reported at editor and compile time (but do not affect compilation).

Now let’s see how do we define an array

Type + array literal definition

Let numArr: number [] numArr = [1, 2, 3] numArr = [1, 2, 3, '4'] / / error: NumArr =[1,2,3,false] Type 'false' is not assignable to type 'number'.Copy the code

Array generics define arrays

Array generics support defining multiple types

Let numArr: Array < string | number > numArr = [1, 2, 3] numArr = [1, 2, 3, '4'] numArr = [1, 2, 3, false] / / error: Type 'false' is not assignable to type 'number'.Copy the code

In real development, it is recommended to define arrays this way because they look cleaner, more flexible, and more like a type

Interface definition array

As mentioned earlier, interface is an important concept that is flexible and can be used in a variety of scenarios. It can be used to define both pseudo-arrays and true arrays, and its type definition is just as flexible as array generics:

Interface NumberArray {[index: number] : number | string} let numArr: NumberArray numArr = [1, 2, 3] numArr = [1, 2, 3, '4'] / / error: NumArr =[1,2,3,false] Type 'false' is not assignable to type 'number'.Copy the code

tuples

Tuple definitions are recommended for arrays that specify the number and type of elements:

Const position: [number, number] = [114.118702, 22.647837] [string, string, string] roleArr= ['superAdmin', 'admin', 'user'] RoleArr = ['superAdmin', 'admin', 'user','tourist'] Type '[string, string, string, string]' is not assignable to Type '. [string,number, Boolean] data= ['superAdmin',0,false] Log (data[0].toString()) console.log(data[1].substring (0,1))// Access elements will automatically obtain their types, so there will be an error: Property 'subString' does not exist on type 'number'.console.log (data[2]) console.log(data[4].toString())  Object is possibly 'undefined'.Copy the code

The enumeration

Here’s an excerpt from Wikipedia:

In mathematical and computer science theory, an enumeration of a set is a program that lists all the members of some finite set of sequences, or a count of objects of a particular type. The two types often (but not always) overlap.

Enumerations are a collection of named integer constants. Enumerations are common in everyday life, such as SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.

Enumeration items have two types: constant items (constant member) and computed items (computed member).

Enumerators are treated as constants if:

  • There is no initialization function and the previous enumerator is a constant. In this case, the current enumerator’s value is the value of the previous enumerator plus one. The first enumeration element is an exception. If it has no initialization method, its initial value is 0.

  • Enumerator members are initialized with constant enumeration expressions. Constant enumerated expressions are a subset of TypeScript expressions that can be evaluated at compile time. An expression is a constant enumerated expression when it satisfies one of the following conditions:

  • Numeric literal

  • Reference to a previously defined constant enumerator (which can be defined in a different enumeration type). If the member is defined in the same enumeration type, it can be referenced by an unqualified name

  • A bracketed constant enumeration expression

  • The +, -, ~ unary operators are applied to constant enumeration expressions

  • The +, -, *, /, %, < <, > >, > > >, &, |, ^ binary operators, constant enumeration expression as its an operation object. If the constant enumeration expression evaluates to NaN or Infinity, an error is reported at compile time

TypeScript enumerations (enums) are flexible and automatically assign values by default, such as defining days of the week:

enum Week {
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday
}
Copy the code

The result after compilation:

var Week;
(function (Week) {
    Week[Week["Monday"] = 0] = "Monday";
    Week[Week["Tuesday"] = 1] = "Tuesday";
    Week[Week["Wednesday"] = 2] = "Wednesday";
    Week[Week["Thursday"] = 3] = "Thursday";
    Week[Week["Friday"] = 4] = "Friday";
    Week[Week["Saturday"] = 5] = "Saturday";
    Week[Week["Sunday"] = 6] = "Sunday";
})(Week || (Week = {}));
//# sourceMappingURL=doc1.js.map
Copy the code

Manual assignment

Values for the digital

When the value is a number, it increments one by one according to manual assignment:

enum Week {
  Monday=1,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday
}
Copy the code

The compiled result is:

var Week;
(function (Week) {
    Week[Week["Monday"] = 1] = "Monday";
    Week[Week["Tuesday"] = 2] = "Tuesday";
    Week[Week["Wednesday"] = 3] = "Wednesday";
    Week[Week["Thursday"] = 4] = "Thursday";
    Week[Week["Friday"] = 5] = "Friday";
    Week[Week["Saturday"] = 6] = "Saturday";
    Week[Week["Sunday"] = 7] = "Sunday";
})(Week || (Week = {}));
//# sourceMappingURL=doc1.js.map
Copy the code

Note that TypeScript doesn’t notice if a value has duplicate entries, so avoid this type of situation:

//TypeScript enum Week {Monday=1, Tuesday, Wednesday=1, Thursday, Friday, Saturday, Sunday} (function (Week) { Week[Week["Monday"] = 1] = "Monday"; Week[Week["Tuesday"] = 2] = "Tuesday"; Week[Week["Wednesday"] = 1] = "Wednesday"; Week[Week["Thursday"] = 2] = "Thursday"; Week[Week["Friday"] = 3] = "Friday"; Week[Week["Saturday"] = 4] = "Saturday"; Week[Week["Sunday"] = 5] = "Sunday"; })(Week || (Week = {})); //# sourceMappingURL=doc1.js.mapCopy the code

The value is string

After a value is assigned to a string, all subsequent values need to be manually assigned (unlike numbers, which are automatically incremented), and incremented only when a value is assigned to a number again:

//TypeScript enum Week {Monday=1, Tuesday='2', Wednesday=3, Thursday, Friday, Saturday, Sunday} (function (Week) { Week[Week["Monday"] = 1] = "Monday"; Week["Tuesday"] = "2"; Week[Week["Wednesday"] = 3] = "Wednesday"; Week[Week["Thursday"] = 4] = "Thursday"; Week[Week["Friday"] = 5] = "Friday"; Week[Week["Saturday"] = 6] = "Saturday"; Week[Week["Sunday"] = 7] = "Sunday"; })(Week || (Week = {})); //# sourceMappingURL=doc1.js.mapCopy the code

Calculated term

Calculated items in enumeration items:

enum Color {
  Red,
  Green,
  Blue = 'blue'.length
}
Copy the code

The above example does not report an error, but if the computed item is followed by an item that has not been manually assigned, an error will be reported because the initial value cannot be obtained:

enum Color {
  Red,
  Green,
  Blue = 'blue'.length,
  Yellow//Enum member must have initializer.
}
Copy the code

Therefore, the computed item must be manually assigned or placed at the end of the enumeration:

enum Color {
  Red,
  Green,
  Blue = 'blue'.length,
  Yellow=3
}
Copy the code

Note that in enumerations with string constants, computed items are not allowed:

enum Color {
  Red,
  Green,
  Blue = 'blue'.length,//Computed values are not permitted in an enum with string valued members.
  Yellow='3'
}
Copy the code

Constant enumeration

Constant enumerations differ from regular enumerations by only one const, except that they are deleted at compile time and cannot contain computed items:

Const enum FiveElements {metal = 'metal ', wood =' wood ', water = 'water ', fire =' fire ', const enum FiveElements {metal = 'metal ', wood =' wood ', water = 'water ', fire =' fire ', Earth = 'earth'} console.log(' Five elements: ${FiveElements. Fire} ${FiveElements. Fire} ${FiveElements. ${FiveElements. Earth} ${FiveElements. Metal} ${FiveElements. ${FiveElements. Water} ${FiveElements. Wood} ') console.log(' FiveElements: ${FiveElements. Earth} ${FiveElements. Earth} ${FiveElements. Earth} ${FiveElements. ${FiveElements. Fire} ${FiveElements. Fire} ${FiveElements. Fire} ${FiveElements. ${FiveElements. Metal} ${FiveElements. Wood} ') console.log(' FiveElements. The ${\ u6728 "" wood / * * /} raw ${\ u706B" "fire / * * /} ${\ u706B" "fire / * * /} raw ${earth" \ u571F "/ * * /} ${\ u571F / * earth * /} ${\ u91D1 "metal / * * /} ${\ u91D1" metal / * * /} raw ${\ u6C34 "" water / * * /} ${\ u6C34" "water / * * /} raw ${\ u6728 / * wood * /} `); Console. log(' Five elements: ${\ u6728 "" wood / * * /} raw ${earth" \ u571F "/ * * /} ${earth" \ u571F "/ * * /} raw ${\ u6C34" "water / * * /} ${\ u6C34 / * water * /} ${\ u706B "" fire / * * /} ${\ u706B" "fire / * * /} raw ${\ u91D1" metal / * * /} ${\ u91D1 "metal / * * /} raw ${\ u6728 / * wood * /} `); //# sourceMappingURL=doc1.js.mapCopy the code

External enumeration

External enumerations refer to enumerations defined with DECLARE that can be referenced externally:

// ts DECLARE enum FiveElements {metal = 'metal ', wood =' wood ', water = 'water ', fire =' fire ', Earth = 'earth'} //main.ts console.log(' Five elements: ${FiveElements. Fire} ${FiveElements. Fire} ${FiveElements. ${FiveElements. Earth} ${FiveElements. Metal} ${FiveElements. ${FiveElements. Water} ${FiveElements. Wood} ') console.log(' FiveElements: ${FiveElements. Earth} ${FiveElements. Earth} ${FiveElements. Earth} ${FiveElements. ${FiveElements. Fire} ${FiveElements. Fire} ${FiveElements. Fire} ${FiveElements. Born. ${FiveElements metal} ${FiveElements. Wood} `)Copy the code

The compilation result is:

//main.js console.log(' Five elements: ${FiveElements. Fire} ${FiveElements. Fire} ${FiveElements. ${FiveElements. Earth} ${FiveElements. Metal} ${FiveElements. Born. ${FiveElements water} ${FiveElements. Wood} `); Console. log(' Five elements: ${FiveElements. Earth} ${FiveElements. Earth} ${FiveElements. Earth} ${FiveElements. ${FiveElements. Fire} ${FiveElements. Fire} ${FiveElements. Fire} ${FiveElements. Born. ${FiveElements metal} ${FiveElements. Wood} `); //# sourceMappingURL=doc1.js.map //enum.js //# sourceMappingURL=doc2.js.mapCopy the code

External enumerations are removed at compile time, often in declaration files, and can be used in conjunction with constant enumerations:

Declare const enum FiveElements {metal = 'metal ', wood =' wood ', water = 'water ', fire =' fire ', earth = 'earth'}Copy the code

conclusion

That’s the end of the TypeScript basics. For those of you who have studied strongly typed languages (Java, C, C ++, etc.), TypeScript is easy to use. Many of the concepts you learned in strongly typed languages (yes, learning, programming, how can you call it 😎😎). To learn from the beginning of the front end of the students, always a bit of pain at the beginning, accustomed to good 😋😋.

Suggestion: oneself write simple procedure practice hand, more familiar with familiar.

In addition, the article may not be comprehensive, incorrect or difficult to understand, please feel free to comment in the comments section 😊😊

In the meantime, everyone, spray gently, after all:

I’m a nickname. I’ll see you next time