“This is the ninth day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”


Why learn TypeScript?

TypeScript is an open source, cross-platform programming language created by Microsoft. It is a superset of JavaScript that extends the syntax of JavaScript and is eventually compiled into JavaScript code.

Key features of TypeScript:

  • Superset: TypeScript is a superset of JavaScript;
  • Type system: TypeScript wraps the typing mechanism around JavaScript, making it a statically typed language.
  • Editor function: enhanced editor and IDE function, including code completion, interface prompt, jump to definition, refactoring, etc.
  • Error: Most errors can be found during the compile phase, which helps debug the program.

TypeScript serves two main purposes:

  • Provide an optional type system for JavaScript
  • Compatibility with current and future JavaScript features.

Here’s a look at how both goals are achieved.

1. TypeScript type system

Why type JavaScript at all?

As we know, JavaScript is a lightweight, interpreted scripting language. It is a weakly typed, dynamically typed language that allows implicit conversions, and only runtime can determine the type of a variable. Because variable types are determined at run time, many errors in JavaScript code are found at run time. TypeScript wraps typing around JavaScript, making it a statically typed language. In TypeScript, not only can you easily reuse JavaScript code, the latest features, but you can also write more robust and maintainable code with optional static typing for error checking.

Here are the top ten most common errors in JavaScript projects, if using TypeScript, then inStage of writingMany JavaScript errors can be found and resolved:Type systems can improve the quality and maintainability of your code. With practice, two things in particular need to be noted:

  • Types are good for code refactoring. They help the compiler catch errors at compile time rather than run time.
  • A type is one of the best forms of documentation, a function signature is a theorem, and a function body is an implementation.

You can assume that TypeScript detects the received type before any operators (operators receive actual data while code is running; In static detection, the operator receives whether the type is supported by the current operator. When TypeScript’s type-detection capabilities cover all code, any changes that break conventions are automatically detected and type errors are suggested. As a result, you can safely modify and refactor your business logic without worrying about making stupid mistakes because of poor thinking.

In some languages, types have unnecessarily complex ways to exist. TypeScript makes it as easy as possible to use them by doing so.

(1) JavaScript is TypeScript

TypeScript is essentially no different from JavaScript. We can think of TypeScipt as JavaScript with type annotations, providing compile-time type safety for JavaScript code.

In effect, TypeScript is an “intermediate language,” because it is ultimately translated into JavaScript, which is then interpreted and executed by the browser. TypeScript doesn’t break JavaScript, though. It just extends it.

To be precise, TypeScript simply standardizes methods in JavaScript:

  • TypeScript just provides a new syntax that doesn’t solve bugs;
  • TypeScript is a new language that takes us far away from the runtime.

(2) Types can be implicit

TypeScript extrapolates as much type information as possible in order to give us type safety at a fraction of the cost of development. In general terms, TypeScript automatically determines the data type even if we don’t explicitly declare the type of a variable. For example, the following code:

let a = 1
a = "996"
Copy the code

This code would report an error in TypeScript because TS would know that a is a numeric type and cannot assign a value of any other type to it. This type of inference is necessary.

(3) Types can be explicit

As stated above, TypeScript makes inferential types as safe as possible. We can also use type annotations to do two things:

  • Help the compiler quickly determine the variable type;
  • By forcing the compiler to compile what we think it should compile, the compiler’s algorithmic analysis of the code matches our understanding of the code.

(4) Types are structured

In some languages, types have unnecessarily complex ways of being, but TypeScript’s types are structured. For example, in the following example, the function will take the arguments it expects:

interface Point2D {
	x: number;
  y: number;
}

interface Point3D {
	x: number;
  y: number;
  z: number;
}

const point2D: Point2D = {x: 10.y: 10}
const point3D: Point3D = {x: 20.y: 20.z: 20}

function takePoint2D(point: Point2D){}

takePoint2D(point2D)  // Correct, exactly match
takePoint2D(point3D)  // Correct, can have additional information
takePoint2D({x: 30})  // Error, missing y
Copy the code

(5) Type error does not affect JS running

To facilitate migration of JavaScript code to TypeScript, TypeScript is compiled as much as possible to JavaScript code by default, even if there are compilation errors. Therefore, we can gradually migrate JavaScript code to TypeScript.

(6) Types can be defined by the environment

One of the goals of TypeScript is to make it safe and easy to use existing JavaScript libraries, and it does this through declarations. TypeScript provides a dynamic yardstick by which to measure our investment in declarations. The more we invest, the more type safety and code cues we get. It is important to note that most popular JavaScript libraries have their own declaration files. I won’t go into declarative files in detail here; there will be an article devoted to them later.

2. Support all future JavaScript features

Although TypeScript is a superset of JavaScript, it keeps up with the ECMAScript standard and thus supports new syntax standards such as ES6/7/8/9. In addition, some grammar is extended on the grammatical level. The TypeScript team is also actively adding support for new features that will become more numerous and comprehensive over time.

Despite TypeScript’s rigor, it doesn’t deprive JavaScript of its flexibility. TypeScript is as flexible as JavaScript because it is compatible with JavaScript. For example, you can define the type any anywhere (which is not recommended, of course). After all, TypeScript’s type-checking rigor can be configured with tsconfig.json.

Build a TypeScript development environment quickly

1. Development tools

Before we start building a TypeScript environment, let’s take a look at typescript-friendly ides. I’ll focus on Visual Studio Code, which I’ve been using for a while.

VS Code is Microsoft’s own son and has the following advantages:

  • Based on the traditional syntax highlighting and auto-completion functions, the intelligent completion based on variable type, function definition and the introduction of modules is extended.
  • Support for running and debugging applications directly on the editor;
  • Git Comands are built in, which can greatly improve the efficiency of collaborative development with Git.
  • There is a rich market for plug-ins, and you can choose the right plug-ins according to your needs.

Because VS Code has built-in version-specific TypeScript language services, it naturally supports TypeScript parsing and type detection, and this built-in service is completely isolated from manually installed TypeScript. VS Code therefore supports different versions of TypeScript by dynamically switching language services between built-in and manually installed versions.

If the current application directory has a different version of TypeScript installed than the built-in service, we can click on the version information in the VS Code bottom toolbar. Thus, the switch between “Use VS Code’s Version” and “Use Workspace’s Version” can be realized at will.

In addition, VS Code provides accurate auto-completion of Code based on TypeScript language services and displays detailed type definitions, greatly improving our development efficiency.

2. Set up the development environment

(1) Code initialization

Install TypeScript globally:

// npm
npm install -g typescript
// yarm
yarn global add typescript
// Check the version
tsc -v
Copy the code

2) Initialize the configuration file:

tsc --init
Copy the code

After execution, a tsconfig.json file appears in the project root directory containing the configuration items for TS (which may vary slightly depending on the version).

{
  "compilerOptions": {
    "target": "es5".// Specify ECMAScript target version: 'ES5'
    "module": "commonjs".// Specify the module to use: 'commonjs', 'AMD ', 'system', 'umd' or 'es2015'
    "moduleResolution": "node".// Select a module resolution policy
    "experimentalDecorators": true.// Enable the experimental ES decorator
    "allowSyntheticDefaultImports": true.// Allow a default import from a module that has no default export set.
    "sourceMap": true.// When the ts file is compiled into the JS file, the map file is generated
    "strict": true.// Enable all strict type checking options
    "noImplicitAny": true.// There is an implicit error in expressions and declarations with the type any
    "alwaysStrict": true.// Check modules in strict mode and add 'use strict' to each file
    "declaration": true.// Generate the corresponding.d.ts file
    "removeComments": true.// Delete all compiled comments
    "noImplicitReturns": true.// Not all return paths of the function have return values
    "importHelpers": true.// Import helper functions from tslib
    "lib": ["es6"."dom"].// Specifies the library files to include in the compilation
    "typeRoots": ["node_modules/@types"]."outDir": "./dist"."rootDir": "./src"
  },
  "include": [                              // Ts files that need to be compiled * means that the file matches ** means that the depth of the file is ignored
    "./src/**/*.ts"]."exclude": [														  // No compiled TS files are required
    "node_modules"."dist"."**/*.test.ts"]},Copy the code

You can add the script command to package.json:

{
  "name": "ts-demo"."version": "1.0.0"."description": ""."main": "src/index.ts"."scripts": {
    "build": "tsc".// Perform compilation
    "build:w": "tsc -w" // Listen for changes
  },
  "author": ""."license": "ISC"."devDependencies": {
    "TypeScript ": "^ 4.1.2." "}}Copy the code

3) Compile the TS code:

tsc index.ts
Copy the code

(2) Configure TSLint

TSLint is a plugin configured with tsLint. json to check and prompt for style when writing TypeScript code. If you have a code style requirement, TSLint is where you come in. Its use steps are as follows:

Install TSLint globally:

npm install tslint -g
Copy the code

Initialize the configuration file with TSLint:

tslint -i
Copy the code

This is the tsLint configuration file. It checks the code against this file. The resulting tsLint. json file has the following fields:

{
  "defaultSeverity": "error"."extends": [
    "tslint:recommended"]."jsRules": {},
  "rules": {},
  "rulesDirectory": []}Copy the code

The meanings of these fields are as follows;

  • DefaultSeverity: Indicates the severity of a warning. If it is set to error, an error will be reported, if it is set to warning, if it is set to off, then TSLint will be turned off.
  • Ty
  • Extends: extends extends: extends a specified default configuration rule.
  • JsRules:Used to configure pairs.jsand.jsxFile verification, configuration rules method is the same as the following rules;
  • Rules:TSLint’s rules for checking code are all configured in this, such as when we don’t allow code to be usedevalMethod, that’s where you configure it"no-eval": true;
  • RulesDirectory: You can specify the rule configuration file, where the relative path is specified.

Finally, this article provides a brief introduction to why you should learn TypeScript and how to quickly set up a TypeScript development environment. The next article will cover common TypeScript types.