In the end, I did not escape the clutches of TS, ha ha ha can not say the clutches, during this period of work, I feel that I am learning new knowledge every day, recently when I looked at the source code, I saw part of the source code is written with TS, I did not touch it before, today I will learn TS.

Article Reference:

Super detailed TypeScript tutorial

TypeScript Tutorial for beginners

Getting started with TypeScript by Yifeng Nguyen

Differences between Typescript and Javascript

The above tutorials are written in more detail, I summed up part of the important knowledge points and my own understanding of the article mainly reference ruan Yifeng teacher’s tutorial to write.

Understand TypeScript

What is TypeScript

TypeScript is a superset of JavaScript that extends JavaScript’s syntax. We all know that Javascript does not define data types when declaring variables; the type of the assignment determines the type of the variable. This approach is useful in small development environments, but as JS grows, it can lead to some unavoidable problems. Data type errors can only be detected at runtime. Ts is a static type checking language that provides type annotations to detect data type errors at compile time.

See my last article on strong and weak typing: Notes on Flow

When I look at TS code, I find that a lot of TS code is actually in JS code after adding type comments, (this is just a beginner’s understanding of TS), very friendly to JS players. Compatibility with JS code.

The difference between TypeScript and javascript

TypeScript is an extension of JavaScript objects.

JavaScript code can work with TypeScript without modification, and a compiler can convert TypeScript code to JavaScript.

TypeScript provides compile-time static type checking through type annotations.

Data in TypeScript requires explicit typing; JavaScript does not.

TypeScript provides default parameter values for functions.

TypeScript introduces the concept of “classes” that are not found in JavaScript.

TypeScript introduces the concept of modules, which encapsulate declarations, data, functions, and classes.

3. Benefits of TypeScript

  1. Static input

Static typing is a feature that can detect errors as developers write scripts. Finding and fixing bugs is a pressing need for today’s development teams. With this capability, developers will be able to write more robust code and maintain it for better quality and clarity.

  1. Large development projects

Sometimes you need to make small incremental changes to your code base to improve your development project. These small changes can have serious and unintended consequences, so it is necessary to reverse them. Refactoring is easier and faster using TypeScript tools.

  1. Better collaboration

When you start a large project, there are many developers, and the number of garbled and error machines increases. Type safety is a feature that detects errors during coding, not at compile time. This creates a more efficient coding and debugging process for the development team.

  1. More productivity

Clean ECMAScript 6 code, auto-completion, and dynamic input are among the factors that help make developers more productive. These features also help the compiler create optimized code.

4. TypeScript features

Type annotation and compile-time type checking: Annotate variable types at compile time

Type inference: Ts does not annotate variable types to automatically infer the type of a variable

Type erasure: Content and interfaces annotated during compilation are erased at run time using tools

Interface: TS uses interfaces to define object types

Enumeration: Used for scenarios in which values are limited

Mixin: Can accept any type of value

Generic programming:

Namespaces: A name is valid only within this zone, and can be reused by other zones without conflict.

Tuple: Tuples combine objects of different types, which is equivalent to an array that can hold different types of data.

Await:

TypeScript basics

1, install,

npm install -g typescript
Copy the code

Ts files with TypeScript React files with the.tsx suffix

Compile:

tsc hello.ts
//hello.ts is the file name
Copy the code

2. Hellow World TS instance

function sayHello(person: string) {
    return 'Hello, ' + person;
}

let user = 'Tom';
console.log(sayHello(user));
Copy the code

In the code above: string is the type of the variable we specify for person. Other syntax is the same as JS.

3. Raw data types

The primitive data types are Boolean, numeric, string, null, undefined, Symbol in ES6, and BigInt in ES10

Bigint An arbitrary precision integer In javaScript, the largest number that number can accurately represent is 2^53. There is no number larger than that, and the largest safe range that number can represent is plus or minus 2^53-1. MAX_SAFE_INTEGER and number.min_safe_INTEger. BigInt can solve this problem, and numbers larger than 2^53 can be represented by BigInt

4. Any value (any)

Any Any value type Like the name, the any value is an indeterminate value for the type. Any is allowed to be assigned to any type. One night back before liberation, and JS. The type of a variable is determined by the data to which it is assigned.

Mix type: Can accept any type of value

Note: In TS, if a variable is not typed, it defaults to any

5. Type Inference

Type inference simply means that in TS syntax if a variable has no type, it is automatically type inferred and if the variable has no value, it is type inferred to be any

Note: If an assignment is not made, it is inferred to be of type any and is not checked at all:

6. Union Types

Multiple data types can be used when using type checking. This means that a variable can define multiple data types. For example:

letPC:string | number; PC = one; pc =1 ;

Copy the code

In the example above, the PC variable is defined as both string and number, which is known as the associative type.

The data types used in a joint type | separated

When TS is not sure which type of the union type the variable is, it can only access properties or methods that are common to all types of the union type: For example, in the example above, if we did not specify PC =one or PC =1, we would get an error using the length attribute, because the length attribute is not a number method and we would not get an error using the string method, because both have a string method.

7. Interfaces

Interfaces are simply used to describe the types of objects. Data types include number, NULL string and other data formats. The types of objects are described by interfaces. Here I use teacher Ruan Yifeng’s example:

interface Person {
    name: string;
    age: number;
}

let tom: Person = {
    name: 'Tom'.age: 25
};
Copy the code

In this case, Person is one of the interfaces we defined. I’ve defined two variables name and age so it’s easier to understand that both the name and age properties are contained in the Person interface and when you call them you call person directly rather than each property individually. A few things to note here:

1. Define the same number of variable attributes as the interface, no more or less

2. An interface can be defined using methods of any attribute

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

In the code above: use [propName: string] to define any attribute that takes a string value.

3. The interface can use readonly to define read-only attributes

 readonly id: number;
Copy the code

Note that the read-only constraint exists the first time an object is assigned, not the first time a read-only property is assigned

8, arrays,

How much of an array is defined in TS

1, type + square brackets “to indicate array:

let fibonacci: number[] = [1.1.2.3.5];
Copy the code

2. Use Array Generic to represent arrays:

let fibonacci: Array<number> = [1.1.2.3.5];
Copy the code

Interfaces can also be used to describe arrays:

nterface NumberArray {
    [index: number]: number;
}
let fibonacci: NumberArray = [1.1.2.3.5];
Copy the code

4, use any to indicate that any type is allowed in the array:

let list: any[] = ['xcatliu'.25, { website: 'http://xcatliu.com' }];
Copy the code

9, functions,

Ts function in js function on the basis of the addition of type check to see a TS function definition

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

In this code, type checking is added to x and y sum, but nothing else is changed.

Note: in TS => is not similar to the arrow function in ES6. On the left is the input type, you need to put parentheses around it, on the right is the output type.

The function parameters of ts must be the same as defined, no more or less

Reference for this section: Type of function

Type assertion

Type Assertion can be used to manually specify the Type of a value. After we use any, the group value specifies what type it is. There are two types of syntax:

valueasType must use this < type > value if used in ReactCopy the code

Use: 1. Assert a union type as one of the types. 2. Assert a parent class as a more specific subclass. 3

Types of assertions

This is a lot of stuff and I’ll write a separate article

11. Declaration document

Here are a few more concepts:

Declaration statement: When we use the syntax of the third-party library, TS does not know this syntax, so we must first write a declaration statement to identify the use of the third-party library

Declaration file: Put all declaration statements into a single file, which is the declaration file. Declaration files must have a.d.ts suffix.

Third party declaration files: Some common declaration files are already written, such as the jQuery file. Download and install it directly

npm install @types/jquery --save-dev
Copy the code

Declare var Declares global variables

Declare Function declares global methods

Declare Class Declares the global class

Declare enum Specifies the global enumeration type

Declare Namespace Declares a global object with child attributes

Interface and type declare global types

Export Export variables

Export Namespace Exports objects with child attributes

Export Default ES6 Export by default

Export = CommonJS Export module

Export as Namespace UMD library declares global variables

Declare Global Extends global variables

Declare Module Extension module

/// <reference /

There’s a lot of separate stuff going on here

12. Built-in objects

Built-in objects in JS are used in TS.

ECMAScript built-in objects: Boolean, Error, Date, RegExp

DOM and BOM built-in objects: Document, HTMLElement, Event, NodeList

These are all directly available in TS.

TypeScript progression

1. Type alias

A type alias is used to give a type a new name

type Name = string;
type NameResolver = () = > string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver) :Name {
    if (typeof n === 'string') {
        return n;
    } else {
        returnn(); }}Copy the code

String literal types

The string literal type is used to constrain the value to one of several strings

3, yuan group

A tuple is an array that can contain different data types.

4, Enumeration (Enum)

The enumeration (Enum) type applies to scenarios where the value is limited within a certain range, for example, there are only seven days in a week, and the color is limited to red, green and blue

5, class,

In ES6, the concept of classes was introduced. Ts also has the concept of classes.

Here are some of the characteristics of the class:

Class: Defines the abstract characteristics of a thing, including its properties and methods

Object: An instance of a class, generated by new

The three main features of OOP are encapsulation, inheritance and polymorphism

Encapsulation: Hides data operation details and exposes only external interfaces. The external caller does not need (or can’t) know the details, and can access the object through the interface provided externally, while ensuring that the external party cannot arbitrarily change the data inside the object

Inheritance: A subclass inherits its parent class. A subclass has all the characteristics of its parent class and some more specific characteristics

Polymorphism: the creation by inheritance of different related classes that can respond differently to the same method. For example, Cat and Dog both inherit from Animal, but each implements its own eat method. At this point, for an instance, we can call the eat method without knowing whether it is Cat or Dog, and the program will automatically determine how to execute eat

Accessors (getters & setters) : Used to change the read and assignment behavior of properties

Modifiers: Modifiers are keywords that qualify the properties of members or types. For example, public represents a public property or method

Abstract Class: An Abstract Class is a base Class that other classes inherit from. Abstract classes are not allowed to be instantiated. Abstract methods in abstract classes must be implemented in subclasses

Interfaces: Common properties or methods between classes that can be abstracted into an interface. An interface can be implemented by a class. A class can only inherit from another class, but can implement multiple interfaces

Use of classes in TypeScript

There are three access modifiers, public, private, and protected

Properties or methods decorated by public are public and can be accessed anywhere. By default, all properties and methods are public

A property or method modified by private is private and cannot be accessed outside the class in which it is declared

Protected attributes or methods are protected, just like private, except that they are accessible in subclasses

6. Generics

A property of a function, interface, or class that does not specify a specific type in advance but specifies the type when it is used.