Let me first explain why I am writing this article.

Variable type error in team collaboration

Write code variable name spelling and other low-level errors, do not prompt errors cause difficult to troubleshoot errors

Non-standard code and poor readability

Typescript is not a fast starter as new knowledge

TypeScript covers a lot of stuff, and it’s not practical to teach it all in a single class, so in this article I’ll give you a primer on how to get started with the language and apply it to your own projects

The goal of this article is to get you to:

Recognize the need to learn typescript

Understand the basics of typescript

To learn a new language, we must first understand what the new language will give usBring what? What are the characteristics?Let’s take a look at what typeScript is by nameWe see typeScript, which breaks down into “type” and “script, “which literally means “type javascript.”

TypeScript is a Microsoft development that makes javascript more standardized and helps developers understand and make applications more robust.

When it comes to learning a new language, look for trends and popularity. Here are some stackOverflow stats:

The world’s most wanted languages to learn

Global salary rankings for all languages

We know from the ICONS above that typescript is very popular, and that learning the language can be a powerful competitive advantage

To save ink, we use TS for typeScript

Why is TS so popular, and what problem does it solve?

Talking about what problems to solve, let’s first discuss some problems encountered in the work

For example, one day we received a demand to do a new demand on the original project, at this time we may need to call the method written by others, in order to figure out the parameter type and usage of the function we need to read other people’s code, the process of reading that is a tired ah, the heart of ten thousand horses galloping; Or read the code you wrote before, after such a long time of polishing, may want to write before yourself why, instant urgent reconstruction idea, very not easy to reconstruct, only to find a lot of call place need to change, and see when running is not an error, it is helpless……

For example, our page is a blank screen and does not report errors. After a long time of investigation, we found that it is a parameter spelling error…..

For example, we call the interface to report an error, full of confidence to the back end said you this interface why always report an error? The results of the back end after the query said that your parameter type was wrong, instant have been hit in the face of the feeling…..

There are plenty of examples of problems that could have been solved or not been solved with typescript

Benefits of working with typeScript

1. Significantly improved development efficiency

2. Fewer bugs

3. Errors are exposed early, at compile time

4. More standard code

5. Documentation is easier

In the process of using TS, we will feel a lot of bugs when we just write the code, the error is exposed in the compile phase; In collaborative development, because the code is more formal, the annotations are more detailed, and even the invocation of certain methods can be documented, we feel comfortable calling existing methods.

What is TS?

Ts contains es5, ES6, ES7 and other knowledge. Ts is not a new language, but a superset of JS, which must be compiled into pure JS to run in the browser.

The core of TS is the **”TYPE”**, with emphasis on the TYPE, which we will discuss below

Is TS hard?

TS is actually easy to master as long as you grasp one core:

What type is assigned to

Having said so much, we certainly can’t wait to learn TS, let’s talk about the basic knowledge of TS

The basics of TS

1. Primitive data type (Boolean, numeric, string, NULL, undefined) type definition

2. Assign arbitrary value types and union types

3. Type inference

4. Object type definitions (interfaces and generics)

5. Function parameter and return value type definition

6. Type definition of built-in JS objects

Raw data types (Boolean, numeric, string, NULL, undefined)

let u: boolean = false; let d: number = 6; Let m: string = 'Tom '; let n: null = null; Let u: undefined = undefined;Copy the code

As above, what type do we want this parameter to be? Just write “: type “after the parameter

We might ask, if we define a type, such as number, where we might assign a value of null or undefined, will there be an error?

Undefined and NULL are subtypes of all types. That is, variables of undefined type can be assigned to variables of any type, so no error will be reported.

// let d: number = undefined;Copy the code

Assign an arbitrary value type or a union type

Sometimes we need to assign multiple types to a parameter, for example, if we don’t want to limit the parameter type, we need to consider:

What if I need to assign multiple types?

“: any” represents any type, so we can assign any type

Let m: any = 'seven '; m = 7;Copy the code

But sometimes we don’t want to type “any type,” we just want to type certain types

At this point, the concept of “union types” is introduced. What is a union type and how to use it?

Literally the joint type is also in line with the variety of types, multiple types between separated with pipeline operators “|”

For example, if you want the argument to be a string or a value, you can write it like this

let n: string | number;
n = 'seven’;
n = 7; 
Copy the code

The same is true for function arguments, which are directly followed by the type

function g(s: string | number): number {    
	return s.length;
}
function a(): void {    
	alert('My name is Tom’);
} 
Copy the code

Did you notice that there’s a type in the function, and what does that type do?You all know that functions have not only parameter types, but also return value types, and this type representsThe return value type of the function.

Type inference

Sometimes, if we do not set the type, TS will do the type inference, based on the first assignment of the data type

Let m = 'seven'; m = 7;Copy the code

In fact, it is equivalent to:

Let m: string = 'seven '; m = 7;Copy the code

So the above definition gives an error because it inferred a string but assigned a value. If no assignment is made, it is inferred to be of type any and is not checked at all:

let n;
n = 'seven’;
n = 7; 
Copy the code

This is also easy to understand, when there is no assignment, there is no way to infer the specific type, you can only infer any type.

Object type definitions (interfaces, generics)

When we talk about object type definitions, we’ll be introduced to the concept of interfaces.

Let’s recall the traditional interface, which is to submit data in the format required by the server.

The interface in Ts is similar, and we can quickly understand the definition of an interface through an example

interface Person {    
	name: string;    
	age: number;
}
let tom: Person = {    
	name: 'Tom',    
	age: 25
}; 
Copy the code

Looking closely at the example above, we see that defining an interface is declared with “interface” followed by an interface name, such as “Person”, with a capital letter. This is the specification and I won’t go into details here.

It is not allowed to define variables with fewer attributes than the interface

interface Person { name: string; age: number; } let Tom: Person = {name: 'Tom '};Copy the code

Additional attributes are also not allowed

interface Person { name: string; age: number; } let Tom: Person = {name: 'Tom', age: 25, gender: 'male '};Copy the code

So, when you’re assigning, the shape of the variable has to be the same as the shape of the interface and that’s not very flexible, because you might have some optional properties in your work, so you can use the optional properties of TS and what’s the optional property? Just add “? “before the “:”. Ok, represents this property is optional

interface Person {    
	name: string;    
	age?: number;
}
let tom: Person = {    
	name: 'Tom’
}; 
Copy the code

Note, however, that the optional attribute should be placed after the determined attribute, otherwise an error will be reported, such as the following is not correct

interface Person {; age? : number; name: string } let tom: Person = { name: 'Tom', age: 25 };Copy the code

However, it is still possible to add properties that do not need to be declared in advance. We can use any property of the TS object, and use [propName: String] to define any property to take a value of type string.

interface Person {    
   name: string;    
   age?: number;    
   [propName: string]: any;
}
let tom: Person = {    
   name: 'Tom',    
   gender: 'male’
}; 
Copy the code

Once any attribute is defined, the type of both the determined attribute and the optional attribute must be a subset of its type

If I have an arbitrary property type, then I have defined an arbitrary property and an optional property that conform to the specification of an arbitrary type. For example, the following is an error because the arbitrary type is a string and the age optional property is number, and number is not a subset of string

interface Person {    
	name: string;    
	age?: number;    
	[propName: string]: string;
}
let tom: Person = {    
	name: 'Tom',    
	age: 25,    
	gender: 'male’
}; 
Copy the code

Only one arbitrary attribute can be defined in an interface. If the interface has more than one type of attribute, you can use the union type:

interface Person {    
	name: string;    
	age?: number;    
	[propName: string]: string | number;
}
let tom: Person = {    
	name: 'Tom',    
	age: 25,    
	gender: 'male’
}; 
Copy the code

Array type

Type + square brackets, array generics

let f: number[] = [1, 1, 2, 3, 5];
let f: Array<number> = [1, 1, 2, 3, 5];

let list: any[] = ['1', 25, { w: '111' }]; 
Copy the code

As you can see from the above example, the same is true for Array types, which are followed by “: type “and can be represented by” type +[]” or “Array< type >”

Objects can be identified by interfaces. Can arrays be identified by interfaces?

Of course you can

[index: type]: type, for example:

interface n {    
	[index: number]: number;
}
let fibonacci: n = [1, 1, 2, 3, 5]; 
Copy the code

Type of function

For functions, we can easily understand the following function parameters and return value type annotation after learning the above various types, I will not go into the details, directly look at the example:

Function declaration

function sum(x: number, y: number): number {    
	return x + y;
} 
Copy the code

Functional expression

let mySum = function (x: number, y: number): number {    
	return x + y;
}; 
Copy the code

Define the shape of a function with an interface

interface SearchFunc { (source: string, subString: string): boolean; } let mySearch: SearchFunc; mySearch = function(source: string, subString: string) { return source.search(subString) ! = = 1; }Copy the code

Sometimes some of the arguments in our function may not be necessary, in a word, just like above, let’s look at examples

function buildName(firstName: string, lastName? : string) { if (lastName) { return firstName + ' ' + lastName; } else { return firstName; }} let tomcat = buildName('Tom', 'Cat '); let tom = buildName('Tom');Copy the code

ECMAScript built-in object

let b: Boolean = new Boolean(1); Let e: Error = new Error('Error occurred '); let d: Date = new Date(); let r: RegExp = /[a-z]/;Copy the code

Built-in objects for DOM and BOM

let body: HTMLElement = document.body; Let allDiv: NodeList = document. QuerySelectorAll (' div '); document.addEventListener('click', function(e: MouseEvent) { // Do something });Copy the code

Having said so much, I can’t wait to have a try

Old trick, install first, use later

The installation of the TS

NPM install -g typescript // Run the above command to install $TSC -v // run this command. If the following Version number is output, the installation is successfulCopy the code

Create a new file for test.ts

Var message:string = "Hello World "console.log(message)Copy the code

After executing TSC test.ts, we can see the JS file compiled automatically

var message = "Hello World";
 
console.log(message);
Copy the code

TS must be compiled into JS to run on the browser

That said, our basic course ended here. Although we didn’t speak, we just typed, but our mouth was dry and we were thirsty for a word

I hope you do three things after reading: favorites, likes, and follows

Welcome to leave your comments in the comments section. If you want to learn more about TS, we will talk about the MASTERY course of TS in the next episode. Look forward to my next episode

In this way