The introduction

If you know anything about nPMTrends.com, you can easily get the following screenshot.

The chart shows TypeScript downloads growing exponentially in five years. The best time to learn TypeScript was probably a few years ago if we were following the fund-buying mentality.

But there’s no going back, so don’t get discouraged, there’s another best time to get TS, and that’s right now.

If you’re a VUE skill owner, it’s worth noting that many projects are refactoring in TypeScript or already are. VUE3 + TS! The future is here!

Small hands a praise 👍, a million monthly 💴

Why TypeScript

Why JavaScript?

Before explaining why TypeScript, let’s review why JavaScript. If you know this section by heart, you can speed read it or skip it.

  • History of naming

Back in late 1994, Netscape set the Internet on fire with the launch of a new web browser, Netscape Navigator [1]. With a vision that the web would be more dynamic [2], company executives recruited Brendan Eich in 1995 to design a glue language for the new browser that would make it easier for web developers to assemble components such as images or plug-ins.

The prototype, originally named Mocha, was created in 10 days in May 1995. In September of that year, the name was changed to LiveScript in the Beta version of Netscape Navigator 2.0. In December of that year, it was renamed JavaScript when deployed in Netscape Navigator 2.0 Beta 3. Mainly to rub off on the Java programming language buzzword [3].

Implication:

[1] : At one point in the mid-1990s, Netscape had a 90% market share that Bengua couldn’t imagine. It probably means that the front end does not need to be compatible. (In 2020, Google’s browser had only 60 percent of the global market.)

[2] : Netscape created a set of standards and technologies that define browsers, including, in addition to JavaScript, the famous HTTP cookies. Cow P! Even if it did, it eventually lost the browser wars. Thankfully, Mozilla Firefox was left to burn.

[3] : JavaScript has nothing to do with Java. It’s you! The heat gene is written in every silver gene!

  • ECMAScript

In November 1996, Netscape submitted JavaScript to Ecma International (European Computer Manufacturers Association) for standardization [1]. The new language standard is called ECMAScript.

Since 1997, ECMAScript has been published almost every year, with the exception of only one radical ECMAScript 4 release in the decade 1999-2009.

During the “lost decade”, ECMAScript fell into disuse as browser vendors made various rules. By the time Ajax came along, ECMAScript was back on the agenda.

In 2015, ES6 codenamed Harmony was launched [2]!

Everything seemed to be coming together.

However, the support for new ECMAScript features varies from browser to browser, so we still need to make conversions in production, such as using Babel to convert ES6 to ES5…… [3]

Implication:

[1] : The birth of JavaScript attracted Microsoft, so Microsoft installed JScript in IE 3.0, JScript is actually a kind of implementation of JavaScript. To avoid a split in language standards, Netscape submitted specifications. (Thumbs up PEACE)

[2] : By 2020, ECMAScript has been released in its 11th edition! Have you mastered ES6 yet?

[3] : Bengua wonders: Would the browser environment be better if Netscape and Microsoft had worked together rather than against each other to create a browser and a scripting language? At least it would be less chaotic! But perhaps chaos is also meant to be fair, and standards are meant to be monopolies. Welcome to discuss ~

Why TypeScript?

With the popularity of Ajax and the revival of JavaScript, more and more large Web applications, JS problems are gradually exposed.

Microsoft’s language developers have found that JavaScript is just a scripting language with a simple design concept and a lack of support for classes and modules, which is not suitable for developing large Web applications.

So Anders Hejlsberg, the father of Delphi and C#, released TypeScript in October 2012.

Its characteristics are as follows:

  1. Extended based on the ECMAScript standard, it is a strict superset of JavaScript.
  2. Added optional static types, classes, and modules.
  3. You can compile to JavaScript or run with JavaScript.
  4. Check at compile time, but do not pollute the runtime.

TS is the embodiment of JS rigor.

Static type, dynamic type, weak type, strong type

Have you ever wondered why computers have so many languages? In fact, they can also be classified according to certain criteria, such as: static type, dynamic type, weak type, strong type.

A picture is worth a thousand words:

This melon simple tabulation:

The name of the features
The static type Do type checking at compile time
Dynamic type Do type checking at runtime
Strongly typed Implicit conversions of variable types are not allowed
Weak type Implicit conversions of variable types are allowed

Here’s a quick question: Do you think TypeScript is strongly typed?

  • Flow tool

Flow is mentioned here in passing. Flow is a type checking tool that Facebook released in 2014 to examine the source code for React. It is also often compared to TS.

TypeScript is more powerful as a complete programming language than Flow. The ecology is also more sound and perfect. Especially when it comes to development tools (backed by Microsoft).

Time is all that matters, and looking back at them from our current perspective, I think we can at least conclude that TypeScript is more popular.

Environment configuration && Hello World

With all that said, is your machete hungry already?

Let’s go back to where we started: Hello World!

  1. The Node to the environment.

Install the Node environment without further ado.

  1. Install the typescript.
npm install -g typescript
Copy the code
  1. The TSC command is used to compile.ts to.js.
tsc hello.ts

# hello.ts => hello.js
Copy the code
  1. Install TS-Node to run the TS code directly in.js.
npm install -g ts-node
Copy the code
  1. Compile and run.
ts-node index.js
Copy the code
  1. Display.

Type & Function

type

Type is one of the foundations of computer language, just like the initials and finals in Chinese, and the main series and definite complement in English.

Boolean, Number, String, Array, Null, Undefined

Still have? Here’s the key:

Enum (enumeration), Any (arbitrary), Unknown (Unknown), Tuple (opposite of Any), void (opposite of Any), Never (not exist)

The following list of codes can feel for yourself.

  • Boolean
let isDone: boolean = false; // ES5: var isDone = false;Copy the code
  • Number
let count: number = 10; Var count = 1;Copy the code
  • String
let name: string = "Semliker"; // ES5: var name = 'Semlinker';Copy the code
  • Array
let list: number[] = [1, 2, 3]; Var list = [1,2,3]; let list: Array<number> = [1, 2, 3]; // ES5: var list = [1,2,3];Copy the code
  • undefined
let u: undefined = undefined;
Copy the code
  • null
let n: null = null;
Copy the code
  • Enum (Enum)

TypeScript supports numeric and string-based enumerations.

/ / number: Enum EnumNum {a, b, C, d,} string enum EnumStr {a = "A ", b = "b", C = "c", d = "d", } {a, b, c = "c", d = 3, e,}Copy the code
  • Any (Any)

In TS, any type can be classified as any. This makes any the top-level type of the type system (also known as the global super type)

let value: any;

value.foo.bar; // OK
value.trim(); // OK
value(); // OK
new value(); // OK
value[0][1]; // OK
Copy the code

Using the any type, you can easily write code that is typed correctly but has problems at run time. If we use any, we won’t be able to use the many protections TypeScript provides. To address the problem of any, TypeScript 3.0 introduces unknown types.

  • Unknown

Unknown becomes another top-level type in TypeScript’s type system.

An Unknown type can only be assigned to any and the Unknown type itself.

let value: unknown;

value = true; // OK
value = 42; // OK
value = {}; // OK

let value1: unknown = value; // OK
let value2: any = value; // OK
let value3: boolean = value; // Error
let value4: number = value; // Error
let value6: object = value; // Error
let value7: any[] = value; // Error
Copy the code

Understanding: An unknown variable can be any variable (assigned to unknown), but not equal to any specific variable (assigned to another value).

  • Tuple (Tuple)

Tuples can be used to define types with a limited number of unnamed attributes. Each attribute has an associated type. When using tuples, you must provide a value for each attribute. In order to visualize the concept of tuples.

let tupleType: [string, boolean];
tupleType = ["Semlinker", true];
Copy the code
  • Void (as opposed to Any)

The void type is like the opposite of any in that it means there is no type. When a function returns no value, you usually see the return type void:

Note that declaring a void variable has no effect because its value can only be undefined or null:

  • Never (used not to exist)

The never type represents the types of values that never exist. For example, the never type is the return type of function expressions or arrow function expressions that always throw an exception or have no return value at all.

function

What is the difference between kangkang TS and JS functions?

Key differences are: function type, optional arguments, function overloading

  • Function types
Let IdGenerator: (chars: string, nums: number) => string; function createUserId(name: string, id: number): string { return name + id; } IdGenerator = createUserId;Copy the code
  • Optional parameters
// Can pass? Function createUserId(name: string, id: number, age? : number): string { return name + id; }Copy the code
  • Function overloading or method overloading is the ability to create multiple methods with the same name and different numbers or types of arguments.

In plain English: according to the different parameters passed, there will be different representations.

Function getInfo(name:string):void; function getInfo(age:number):void; Function getInfo(STR :any):void{if(typeof STR == "string"){console.log(" name :", STR)} if(typeof STR == "number"){function getInfo(STR :any):void{if(typeof STR == "string"){console. Console. log(" age ", STR)}} getInfo("zhangsan")Copy the code

Not only functions can be overloaded, but methods can also be overloaded. The idea is to follow the overload table until it is legal, and more exploration is possible.

  • TypeScript function overloading
  • Method overloading

Interfaces and classes

interface

Interface is a very important concept. As we all know, the docking interface is the most important part to realize functions. Now front-end agile development is more about component reuse, interface reuse may be a direction.

In addition to abstracting some of the behavior of a class, TypeScript interfaces are often used to describe shapes of objects.

  • A typical example
interface Shape {
    head: string;
    arm: string;
}
interface Human {
    name: string;
    age: number;
    shape: Shape;
    say(word: string): void;
}

let jack: Human = {
    name: 'Jack',
    age: 18,
    shape: {
        head: 'head',
        arm: 'arm'
    },
    say(word: string) {
        console.log(word)
    }
}
jack.say('hi')

Copy the code
  • The function interface
interface Fn {
    (a: number, b: number): number;
}

let add: Fn = function(a: number, b: number): number {
    return a + b
}

console.log(add(1, 2))
Copy the code
  • Inheritance of interfaces
interface Animal {
    move(): void;
}

interface Human extends Animal {
    name: string;
    age: number;
}

let jack: Human = {
    age: 18,
    name: 'Jack',
    move() {
        console.log('move')
    }
}
Copy the code

class

A class is a construct of an object-oriented computer programming language. It is a blueprint for creating objects, describing the common properties and methods of the objects created.

Js has no classes in the strict sense, and ES6’s class implementation inherits nothing more than syntactic sugar based on prototype chains. Interested in understanding the underlying implementation. In TS, the same is true. Interested in reading about the differences between TypeScript and classes in ES6

Here is the direct conclusion:

Two key points: Abstract classes, access qualifiers (interface inheritance explained above)

  • An abstract class

We all know that JAVA is a typical object-oriented, with four features: abstraction, encapsulation, inheritance, polymorphism, but also a large number of people in the process of learning TS think that it is very similar to JAVA, which is very important because TS also has abstract classes.

In object-oriented concepts, all objects are represented by classes, but conversely, not all classes are represented by objects. If a class does not contain enough information to represent a concrete object, such a class is an abstract class.

Recommended reading: Object-oriented programming in TypeScript

Abstract classes are represented in TypeScrupt using the abstract modifier.

abstract class Animal{ public name:string; constructor(name:string){ this.name=name; } abstract eat():any; Run (){console.log(' non-abstract method, no need to subclass, override '); }Copy the code
  • Access qualifier
class Dog { constructor(name : string) { this.name = name; } public name : string; // Modifier public member, visible to all private pri(){}; Protected pro() {}; // Protected pro() {}; Readonly legs :number = 4; readonly legs :number = 4; Static food: string = "bones"; static food: string = "bones"; Static members of a class can be inherited from run (){}}.Copy the code

Namespace & module

The namespace

A namespace defines the visible scope of an identifier. An identifier can be defined in multiple namespaces, and its meaning in different namespaces is irrelevant. We can place functions, classes, interfaces, and so on with similar functionality into namespaces. If you want access outside of the namespace, export.

We declare namespaces with the keyword namespace,

  • namespace
// IShape. Ts namespace Drawing {export interface IShape {// If we want to call the class and interface, we need to add the export keyword to the class and interface. draw(); } } // Circle.ts /// <reference path = "IShape.ts" /> namespace Drawing { export class Circle implements IShape { public  draw() { console.log("Circle is drawn"); }}}Copy the code

If a namespace is in a separate TypeScript file, it should be referenced with a triple slash /// in the following syntax:

/// <reference path = "SomeFileName.ts" />
Copy the code
  • Nested namespaces
Example Namespace namespace_name1 {export namespace namespace_name2 {export class class_name {}}}Copy the code

The module

In TypeScript, as in ECMAScript2015, any file that contains a top-level import or export is treated as a module. Well, it doesn’t have to be the top. So that’s a brief overview of what a module is. — Official documents

Export interface StringValidator {isAcceptable(s: string): Boolean; } export const numberRegexp = /^[0-9]+$/; Export class ZipCodeValidator implements StringValidator {isAcceptable(s: s) String) {return s.length === 5 && numberRegexp. Test (s)}} export {StringValidator, numberRegexp, Export default function Test (s: string) export default function Test (s: string) : Boolean {return s.length === 5} import{StringValidator, numberRegexp, Import * as validator from "./ZipCodeValidator" let zip = new Validator. ZipCodeValidator () / / if export is the default, you can import it directly import the test from ".. /.. /xxx.js"Copy the code

Consistent with ES6.

  • Best practices

In modules, the best practice is to export a new entity to provide new functionality (that is, module extensions).

//Calculator.ts export class Calculator { private current = 0; private memery = 0; private operator: string; ProcessDigit (digit: string, currentValue:) number){ if(digit >= "0" && digit <= "9"){ return currentValue * 10 + (digit.charCodeAt(0) - "0".charCodeAt(0)) } } } Import {Calculator} from "./Calculator" class ProgrammerCalculator extends Calculator {static digits = ["0", "1", "2", "3", "4"); constructor(public base: number){ super() if(base <= 0 || base > ProgrammerCalculator.digits.length){ throw new Error ("base has to be within 0 to 16 inclusive") } } protected processDigit(digit: string, currentValue: Number) {if (ProgrammerCalculator. Who. IndexOf (digit) > = 0) {/ / there are digit return currentValue. * this base + ProgrammerCalculator. Who. IndexOf (digit) / / custom extensions to calculate}}} / / export export {ProgrammerCalculator as Calculator} // Do not use namespaces in modulesCopy the code

How does it apply to Vue projects?

The use of TS in the Vue project is based on decorators, which provide a way for us to add annotations to class declarations and members through metaprogramming syntax. Vue decorator writing

  1. Change the entry file main.js to main.ts and change webpack.config.js
const path = require('path')
module.exports = {
  ...
  pages: {
    index: {
      entry: path.resolve(__dirname+'/src/main.ts')
    },
  },
  ...
}
Copy the code
  1. Add decorator
npm install vue-class-component vue-property-decorator -D
Copy the code
  1. Transform the vue
<script lang="ts"> import { Component, Vue, Prop, Watch } from "vue-property-decorator"; import draggable from 'vuedraggable' @Component({ created(){ }, components:{ draggable } }) export default class MyComponent extends Vue { /* data */ private ButtonGroup:Array<any> = ['edit', 'del'] public dialogFormVisible:boolean = false /*method*/ setDialogFormVisible(){ this.dialogFormVisible = false } addButton(btn:string){ this.ButtonGroup.push(btn) } /*computed*/ get routeType(){ return this.$route.params.type } @Prop({type: Number,default: 0}) readonly id! : @watch ('dialogFormVisible') dialogFormVisibleChange(newVal: Boolean){// Some actions}} </script>Copy the code

See vue-property-decorator for more on the use of decorators

summary

This is an introductory TypeScript tutorial, and while it’s not complete, the overall focus is highlighted and Talk is cheap. If the historical perspective of the first chapter appeals to you, that’s great.

Bengua’s understanding of TypeScript is that JavaScript as a scripting language can no longer support the normative development of large applications because of the growth of the front end. Drawing lessons from the object-oriented thought (abstraction, encapsulation, inheritance, polymorphism) of Java, which is a successful model for developing large applications, TS strictly defines different types, standardizes the transmission of parameters, implements abstract classes, implements interface inheritance, and optimizes the idea of modularization.

We can imagine that with the collaborative development of TS front-end projects, the code will be more reusable, readable, easy to maintain, and more productive.

Productivity determines wealth! Early to learn, early to enjoy! May you and I both live with beautiful code!

Reference documentation

  • JavaScript- Wikipedia
  • Browser wars – Wikipedia
  • ECMAScript- Wikipedia
  • What is the difference between weakly typed, strongly typed, dynamically typed and statically typed languages?
  • Strongly typed JavaScript solution
  • Great TypeScript tutorial for getting started
  • Vue + TypeScript + Element project
  • Use decorators in Vue