preface

In recent years, the front end of TypeScript has become increasingly popular, especially with Vue3 being rewritten in TypeScript. TypeScript seems to have become a must-have skill, otherwise you won’t be able to look at Vue3 source code. Answers like “I don’t want to use JavaScript since I started using TypeScript”, “If you use ES6, TypeScript can be accessed almost without barriers”, and “TypeScript can replace JS in any scenario” are common. I recently attended the first Byte Front End Youth Camp, where I started learning about TypeScript. This article is a learning note. If there are any errors, please point out ~🧐

First, TypeScript basics

1.1 Development environment construction

Initialize the first TypeScript project

npm init -y 
npm install --save-dev typescript # The latest stable version
npm install --save-dev typescript@next # version early adopters
Copy the code

Create the tsconfig.js file

Methods a: Create first.tsFile, then click on the TypeScript version number in the lower right corner of VsCode. A drop-down menu will appear and click createtsconfigChoice, like thistsconfigThe file has been created tsconfig.jsonThe files are as follows πŸ‘‡ :

{
  "compilerOptions": {
    "module": "commonjs"."target": "es2020"."jsx": "preserve"."strictFunctionTypes": true."sourceMap": true
  },
  "exclude": [
    "node_modules"."**/node_modules/*"]}Copy the code

Method 2: go to node_modules/.bin/ TSC and run –init locale zh-cn to generate the tsconfig file

Select the TypeScript version

We choosenode_modulesThe version in the directory.After the version is selected, it will be generated in the root directory.vscodeFolder. It’s gonna be in theresettings.jsonFile.

1.2 tools

TS Playground

TypeScript officially provides us with a tool for testing TS code :TS Playground. See the following figure: πŸ‘‡

Equal<x,y>

This tool allows you to see if the types of two type names are equal.

1.3 Preliminary Knowledge

TS and JS

Let’s be clearTypeScriptisJavaScriptA superset of,TypeScriptAll JavaScript features are provided and added on top of itTypeScriptThe type system.

This type system is designed to be “optional”. This means that all legitimate JavaScript code is legitimate TypeScript code.

TS compilation process

‘TS type checking’ and ‘JS generation’ are two separate processes; Type checking errors do not affect generating JavaScript code!

So it is different from C, C++ and other languages!

The type system

We need to be clear that TS uses the structural type system, so what is the structural type system?

Structural Type System

Through the type of the actual structure to determine whether two types are equal or compatible (TypeScript, Haskell, Go, etc.)

Nominal Type System

Determine whether two types are equal by their name (C,C ++, Java,C#,Rust,…)

Type annotations

The type annotation for TS is also something we need to know, which is different from other languages: πŸ‘‡

// C++ comes first
int printf( constchar*, ...) ;// Objc comes first with parentheses
- (id)initWithInt:(int)value;

// Put Julia after it with double colons
commission(sale::Int,rate::Float64)::Float64

// TypeScript also comes after, with double colons
function log(message: string) :void
Copy the code

The relationship between types and collections

See the table below for details

TypeScript term Set term
nerver empty set
Lieral type Single element set
Value assignable toT The Value ∈ (member of T)
T1 assignable to 2 T1 βŠ† T2 (subset of)
T1 extends T2 T1 βŠ† T2 (subset of)
T1|T2 T1 βˆͺ T2
T1&T2 T1 studying T2 (intersection computes)
unknown Universal set

Type the alias

In JS, you can yong let, const, var to declare variables or constants. In TS, you can yong type to declare aliases for types

Type aliases are similar to let variables in that they have block-level scope. Therefore, the same name cannot be in the same scope.

Type broadening and narrowing

Design for the design of the design

When you assign a literal to a let or var variable, TS does not use the literal type as the type of the variable. It broadens from literal types to correspondingly broader types. This process is called type broadening.

Type Narrowing:

In some cases, TS can be more specific about the type of the variable, in which case it will narrow it down. TS tries to strike a balance between type certainty and flexibility. TS provides a number of methods to help narrow types to improve type determinism:

  • null check
  • ad const
  • instanceof
  • typeof
  • Property to check
  • Tagged Union
  • User type guard
  • Code stream

When a variable is declared with let var, TS believes that the variable will change in the future, so the type is inferred as a corresponding broad type. When declaring a variable with const, TS knows that constants are invariant and extrapolates the type to the narrowest literal type.

Value types and type Spaces

We can think of the type space as the various types that exist at compile timeTypeScriptThe compiler inside TSC creates the value space byJSEngine such asV8Created by the engine, which holds various values at run time.

A namespace that contains only type declarations does not generate JS code and does not introduce variables. The instanceof operator operates only on value Spaces.

How do you figure out which space it’s in?

  1. Code that disappears after translation — > type space
  2. Symbol for type annotations, aliases — > type space
  3. Symbol after type assertion — > Type space (Target as/is HTMLElement)
  4. Const,let,var symbol — > value space
  5. Class,enum, symbol after namespace — > value space + type space

The type hierarchy in TS

See the following figure πŸ‘‡ :

A value of a lower type can be assigned to a variable/constant of an upper type. A change/constant of unknown type can point to a value of any type.

Compare Top Type and Bottom Type in different languages

So, that’s the end of the TypeScript prep

The last

⚽, we are done with TypeScript preparation. ⚾ we will update the basics of TypeScript later. Interested students can click to follow + favorites, more wonderful knowledge is waiting for you ~ πŸ€GitHub blog address: github.com/Awu1227. πŸ‰ I have other columns, please read ~ 🏐 play the beauty of CSS 🎱Vue from giving up to getting started 🎳 simple JavaScript