Before reading this article, I highly recommended the TypeScript Tutorial. Because this book is: Thinking from a JavaScript programmer’s point of view, step by step understanding TypeScript. The source of the article is also the same book, but take a word from me: stepping on the pit means you know. [Suggested collection]

Hopefully you have the following skills before you read this book:

  • Proficient in JavaScript for daily project development

What is TypeScript?

1. TypeScript word solutions

Typed JavaScript at Any Scale.

JavaScript with a type system added for projects of any size.

This is what TypeScript’s website [1] defines. Two important features were highlighted:

  1. The type system
  2. Suitable for any size

2. TypeScript features

1. Type system

As the TypeScript name suggests, “type” is at the heart of TypeScript.

As we know, JavaScript is a very flexible programming language (weakly typed) :

  • Without type constraints, a variable may start as a string and be assigned a number later.
  • Implicit conversions can move variable types around at run time.
  • Object-oriented programming based on prototypes allows properties or methods on prototypes to be modified at run time.
  • Functions are first-class citizens of JavaScript and can be assigned to variables, as arguments, or as return values.

This flexibility is like a double-edged sword. On the one hand, JavaScript thrives on everything (apps, desktops, applets, websites, frameworks, servers). On the other hand, the maintenance cost is high due to the uneven code.

TypeScript’s type system largely compensates for JavaScript’s shortcomings.

TypeScript is static

The type system is divided into dynamic types and static types according to “type checking timing.”

Dynamic typing means that type checking is done at run time, and type errors in this language often result in runtime errors. JavaScript is an interpreted language and has no compile phase, so it is dynamically typed.

let foo = 1; foo.split(' '); // Uncaught TypeError: foo. Split is not a function // Foo. Split is not a functionCopy the code

Static typing means that the type of each variable can be determined at compile time. In this language, typing errors often result in syntax errors. TypeScript needs to be compiled to JavaScript before it can be run, and TypeScript is typed statically. TypeScript code will report errors at compile time:

let foo = 1; foo.split(' '); // Property 'split' does not exist on type 'number'. // Property 'split' does not exist on type 'number'Copy the code

This TypeScript code looks like JavaScript.

In fact, most JavaScript code can become TypeScript code with little or no modification at all, thanks to TypeScript’s powerful “type inference”, even if you don’t manually declare the type of variable foo, It can also automatically infer that a variable is of type number when it is initialized.

The full TypeScript code looks like this:

let foo: number = 1; foo.split(' '); // Property 'split' does not exist on type 'number'. // Property 'split' does not exist on type 'number'Copy the code

TypeScript is weak

The type system is divided into strong and weak types according to whether implicit type conversions are allowed.

The following code works in both JavaScript and TypeScript. At runtime the number 1 is implicitly typed to string ‘1’, and the plus sign + is recognized as string concatenation, so the result is the string ’11’.

console.log(1 + '1'); // Print out the string '11'Copy the code

TypeScript is fully javascript-compatible and does not modify JavaScript runtime features, so they are weakly typed.

By contrast, Python is strongly typed, and the following code will report an error when run:

print(1 + '1')
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
Copy the code

To fix this error, perform a cast:

Print (STR (1) + '1')Copy the code

No matter what type is on either side of the plus sign in JavaScript and TypeScript, implicit type conversions can compute a result — not an error — so both JavaScript and TypeScript are weakly typed.

Although TypeScript is a weak type, we can take advantage of the type system TypeScript provides and the code-checking capabilities ESLint provides. Makes TypeScript more of a “strong type.”

Such a type system represents the core design philosophy of TypeScript: to improve the maintainability of code and reduce bugs by introducing a static type system while preserving JavaScript runtime behavior intact.

2, applicable to any scale

TypeScript is ideal for large projects, where the type system provides greater maintainability and fewer bugs.

In small and medium-sized projects, due to type inference, most types do not need to be manually declared, so it will not greatly reduce the development efficiency, so some small and medium-sized enterprises will also choose it.

TypeScript can also coexist with JavaScript. If you’re an old JavaScript project and you want to make a TypeScript project, but the code is too large and the project needs to be updated. So you can have new content and files in TypeScript, old ones unchanged. When you are free, you can gradually upgrade old files to TypeScript one by one.

In fact, even if you’ve never learned TypeScript, you may already be using TypeScript unconsciously — when writing JavaScript in the VSCode editor, Features such as code completion and interface hints are implemented through TypeScript Language Services:

Some third-party libraries, such as Vue 3.0, support TypeScript natively and can be used with code completion:

Some third-party libraries don’t support TypeScript natively, However, code completion can be achieved by installing community-maintained type declaration libraries (such as the React type declaration library by running NPM install — save-dev@types /react) — both in JavaScript projects and in JavaScript projects This is supported in TypeScript projects:

As you can see, TypeScript has grown so deeply into the front-end community that projects of any size are supported by TypeScript to a greater or lesser extent.

3. Synchronous development with standards

Another important feature of TypeScript is its adherence to the ECMAScript standard.

ECMAScript is the standard for JavaScript’s core syntax. Since 2015, a new version has been released every year, including some new syntax.

A new syntax goes through the following stages from proposal to standard:

  • Stage 0: No formal proposals, only discussions and ideas.
  • Stage 1: Consultation Stage, providing abstract API descriptions, discussing feasibility, key algorithms, etc.
  • Stage 2: The draft Stage, where the syntax and semantics are described precisely in the formal specification language.
  • Stage 3: Candidate Stage, syntax design has been completed, requires browser, Node.js and other environment support, collect user feedback.
  • Stage 4: Finalized, ready to be added to the formal ECMAScript standard.

TypeScript implements a syntax as it enters the Stage 3 phase. On the one hand, it allows us to use the latest grammar as early as possible to help it move to the next stage. On the other hand, the syntax in Stage 3 is stable and there is no change in syntax, which makes it easy to use.

In addition to implementing the ECMAScript standard, the TypeScript team has also advanced several syntax proposals, such as optional chain operators (? .). , null value merge operator (??) Throw expressions, regular matching indexes, and so on.

How do I install TypeScript and editor recommendations

Install TypeScript

TypeScript command-line tools are installed as follows:

NPM install -g typescript # or use YARNCopy the code

The above commands will install the TSC command in the global environment, and after the installation is complete, we can execute the TSC command anywhere.

Compiling a TypeScript file is simple:

tsc hello.ts
Copy the code

We have a convention that files written in TypeScript end with.ts and React end with.tsx.

2. Editor

One of the biggest advantages of TypeScript is its enhanced editor and IDE capabilities, including code completion, interface hints, jump to definitions, refactoring, and more.

Major editors support TypeScript, so I recommend using Visual Studio Code.

It is an open source, lightweight cross-terminal editor with built-in TypeScript support. No need to compile phase, you can see if it’s right after you write it.

​​

Error: Number has no length attribute.

Vscode itself is also written in TypeScript.

Visual Studio Code-code Editing. Redefined

The first example is Hello TS

Let’s start with a simple example.

Copy the following code into hello.ts:

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

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

Then perform

tsc hello.ts
Copy the code

A compiled file hello.js is generated:

function sayHello(person) {
    return 'Hello, ' + person;
}
var user = 'TS';
console.log(sayHello(user));
Copy the code

In TypeScript, we use: to specify the type of a variable, with or without Spaces before:.

In the example above, we specify the person argument type to string with:. But after compiling to JS, no checking code is inserted.

This is because TypeScript only statically checks types at compile time, and if errors are found at compile time (the process of converting TS files to JS) an error is reported. At run time, like normal JavaScript files, there is no type checking.

If we need to guarantee the type of the argument at runtime, we still have to check the type manually:

function sayHello(person: string) {
    if (typeof person === 'string') {
        return 'Hello, ' + person;
    } else {
        throw new Error('person is not a string');
    }
}

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

Try compiling this code:

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

let user = [0, 1, 2];
console.log(sayHello(user));
Copy the code

An error will appear in the editor, and an error will occur at compile time:

But the js file is still generated:

function sayHello(person) {
    return 'Hello, ' + person;
}
var user = [0, 1, 2];
console.log(sayHello(user));
Copy the code

This is because TypeScript compilations generate compilation results even if errors are reported, and we can still use the compiled file.

If you want to stop generating js files when an error is reported, you can configure noEmitOnError in tsconfig.json. For tsconfig.json, please refer to the official manual (Chinese version). We’ll explain where sconfig.json comes from later in the TypeScript primitive data type.

TypeScript basics

1. Raw data type

Raw data types · TypeScript

PS: null value:

The difference with void is that undefined and null are subtypes of all types. (tsconfig.json: strict set false) (tsconfig.json: strict set false)

2. Any value

Any value · TypeScript

3. Type inference

Type inference · TypeScript

4. Association type

Associative types · TypeScript

Note that once an optional attribute is defined, all other attributes in the same interface must be a subset of the optional attribute. Otherwise, an error will be reported. Collective concept: string | number, for example, number of its subsets, the string is a subset of the for it.

Another version problem:

5. Object type – interface

Object type — interface · TypeScript

6. Array type

Array types · TypeScript

PS: Confused? { [index: number]: number; length: number; callee: Function; }

Callee can be Function.

7. Type of function

Function types · TypeScript

Type assertion

Type assertions · TypeScript

9. Declaration documents

Declare files · TypeScript

10. Built-in objects

Built-in objects · TypeScript

TypeScript progression

Advanced TypeScript

Four,

Cough, steal a lazy, not to list one. Again, I highly recommend getting started with TypeScript. You still have to learn TypeScript through it. In addition to the above, it also includes engineering configuration instructions. I by my younger brother’s personality guarantee, see it will! Blunt XDM!

🔥 Previous articles recommended:

Teach you how to use JSX in Vue Paper Plane Blog -CSDN blog

Several interviews in 2021 have left me with 17 JS handwritten questions! _ Paper Plane Blog -CSDN blog

Paper Plane blog -CSDN blog

❤️ talk about macro tasks and micro tasks in JS! _ Paper Plane Blog -CSDN blog

Front-end efficient development has to know some JavaScript libraries! _ Paper Plane Blog -CSDN blog