Quickly learn TypeScript in 30 minutes


1. What is TypeScript?


TypeScript is a superset of JavaScript, which adds common concepts such as classes, modules, interfaces, generics, and static types (optional) to JavaScript.


To distinguish between dynamic and static programming languages, TypeScript is a statically typed programming language, and JS is a dynamically typed programming language. Static typing requires type checking during compilation, and dynamic typing involves type checking during execution.


All JavaScript code is valid TypeScript code. Any JavaScript project can seamlessly introduce TypeScript. The TypeScript compiler will eventually compile TypeScript code into JavaScript code.


This article only focuses on TypeScript's additional syntax that differentiates it from JavaScript.


2. Why use TypeScript?


1. OOP object-oriented features

TypeScript should feel familiar to people with an OOP (object-oriented programming) background. In fact, the engineers who developed TypeScript were the Microsoft engineers who led the development of C#, but the engineers were careful to only borrow features that were meaningful to TypeScript. In fact, TypeScript More like JavaScript itself.


2. Improved development efficiency

Admittedly, a TypeScript project will have more lines than the equivalent JavaScript code, but it helps describe the data you're manipulating, thereby reducing the overall cognitive cost. It increases development speed by reducing memory costs and eliminating manual inspection types by opening irrelevant files.


3. Detailed introduction to TypeScript


1. Boolean type

let isVisable: boolean = false;

2. Numeric type

let count: number = 20;


3. String type

let name: string = 'xiaowang';

If you don't know the type, you can use "any" (any) type

let sure: any = 5;
sure = '重新赋值转换为字符串类型';
sure = false;       // 还可以重新定义为布尔类型

4. Constant

Use the const keyword to modify a literal value as a constant.

const num = 9;
num = 1; 			// 常量不能重新被赋值,这里会报错

5. Array

Arrays in TypeScript have two representations, one is a typed array and the other is a generic array.

Typed array:

// 
let list: number[] = [1, 2, 3];


Generic array:

let list: Array<number> = [1, 2, 3];

6. Enumeration

enum Color {Red, Green, Blue}
let c: Color = Color.Green;

7. void keyword

It is used to indicate that a function does not return any value:

function Alert(): void {
  alert('我是弹出框!');
}

8. Function

Support for lambda fat arrow expressions and type inference

General functions

let fun1 = function(n: number): number { return n * n; };

Infer function return type based on return value

let fun2 = function(n: number) { return n * n; };

fat arrow expression

let fun3 = (n: number): number => { return n * n; };

Fat arrow expressions that infer the return type from the return value

let fun4 = (n: number) => { return n * n; };

The fat arrow expression that infers the return type based on the return value, while omitting the curly braces, the return keyword can be omitted at the same time

let fun4 = (i: number) =>  i * i;

9. Interface

Interfaces are structured, and any object that has all the properties declared in the interface is compatible with the interface.

interface Student {
  name: string;
  age?: number;    // 使用 "?" 标识,表明该属性是一个非必需属性
  move(): void;    // 函数
}

An object implementing the "Student" interface can be regarded as a "Student" when it has a "name" attribute and a "move" method

let p: Student = { name: 'xaioming', move: () => {} };

Object with optional properties

let smallStudent: Student = { name: 'xaioming', age: 5, move: () => {} };

The following example is not a "Student" because the type of the "age" attribute of the object is not "number"

let invalidStudent: Student = { name: 'Bobby', age: true };

An interface can also describe the type of a function

interface FindFunc {
  (source: string, subString: string): boolean;
}

The parameter name is not important, the parameter type is important

let myFind: FindFunc;
myFind = function(src: string, sub: string) {
  return src.search(sub) !== -1;
};

10. Class

Class member access permissions are public by default.

Class constructor - Variables decorated with public/private keywords in the class constructor will be declared as member properties of the class.

The following example: age will be declared and defined as a class member attribute like name, and no additional code is required.

class Student {

  name: string;   // 成员属性

  constructor(name:string, public age: number=1) {
    this.name = name;
  }

  // 成员函数
  move() { retun this.age++;}

  // 静态成员
  static normal = new Student('xiaoming', 10);
}

let p1 = new Student('xiaowang', 12);
let p2 = new Student('xiaoxi');      // age 为构造器中指定的默认值:1

Class inheritance

class BigStudent extends Student {
  constructor(name:string,  age: number, public major:string="计算机") {
    super(name, age); // 必须显式调用父类的构造函数
  }

  // 重写父类中的 dist() 函数
  dist() {
    let d = super.dist();
    return d+d;
  }
}

11. Module

The module "." symbol can be used as a submodule separator:

module Geometry {
  export class Square {
    constructor(public length: number = 0) {
    }
    area() {
      return Math.pow(this.length, 2);
    }
  }
}

let s1 = new Geometry.Square(6);

Create a local alias for the module:

import G1 = Geometry;
let s2 = new G1.Square(2);

12. Generics

class generic

class Student<T1, T2> {
  constructor(public param1: T1, public param2: T2) {
  }
}

Interface generics

interface Student<T> {
  param1: T;
  param2: T;
}

function generics

let student2 = function<T>(p: Student<T>) {
  return new Student(p.param1, p.param2);
};


let tuple = student2({ param1: 'hello', param2: 'world'});

13. Template string

String using backtick

// 嵌入变量的模板字符串
let name = 'wangming';
let greeting = `Hi ${name}, how are you?`;

// 有多行内容的模板字符串
let multiline = `This is an example
of a multiline string`;

14. Reference definition files

<reference path="jquery.a.ts" />

References:


Guess you like

Origin blog.csdn.net/lizhong2008/article/details/132578644