Typescript

使用分享

Created by gavinxgu

什么是Typescript?

“TypeScript is an open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language.” -- Wikipedia

TypeScript是Microsoft开发和维护的一种开源编程语言。他是JavaScript的一个严格的语法超集,并增加了可选的静态类型。

为什么要使用静态强类型语言?

  • 动态弱类型传参类型错误,会引发运行时的报错,花费的时间太多;
  • 动态弱类型还缺乏编辑器IDE集成,因为在没有静态类型的情况下,很难实现跳转定义、自动重构以及其他功能;
  • 静态强类型我们可以先设计数据类型,然后我们的代码就会“自然成型”;
  • 在编写库文件或多人协作项目时,降低协作者和使用者的学习使用成本;
  • TS over JS - 基本类型

                  
                    let isDone: boolean = false; // Boolean
                    let decimal: number = 6; // Number
                    let color: string = "blue"; // String
                    let list: number[] = [1, 2, 3];
                    let list: Array<number> = [1, 2, 3]; // Array
                    let x: [string, number] = ["hello", 10]; // Tuple
                    enum Color {Red, Green, Blue};
                    let c: Color = Color.Green; // Enum
                    let notSure: any = 4; // Any
                    let unusable: void = undefined; // Void: you can only assign undefined or null to them
                    let u: undefined = undefined; // Undefined
                    let n: null = null; // Null
                    function error(message: string): never {
                      throw new Error(message);
                    } // The never type represents the type of values that never occur
                    declare function create(o: object | null): void; // Object
                    let someValue: any = "this is a string";
                    let strLength: number = (<string>someValue).length; // Type assertions
                  
                

    TS over JS - 接口(Interfaces)

                          
                            interface Name {
                              firstName: string;
                              lastName: string;
                            }
            
                            interface MiddleName extends Name {
                              middleInitial: string;
                            }
    
                            interface Person {
                              name: MiddleName;
                              sex: "male" | "female";
                              age: number;
                            }
                          
                        
    1. 接口可以定义一个数据结构
    2. 可以被类和接口继承(extends)
    3. 可以被类实现(implements)

    TS over JS - 类(Classes)

                        
                          class Student implements Person {
                            static isStudent: true;
                            public age: number;
                          
                            get fullName() {
                              return (
                                this.name.firstName +
                                " " +
                                this.name.middleInitial +
                                " " +
                                this.name.lastName
                              );
                            }
                          
                            constructor(
                              public name: MiddleName,
                              age: number,
                              public sex: "male" | "female" = "male",
                              public job?: string
                            ) {
                              this.age = age;
                            }
                          }
                        
                      
    1. Public, private 和 protected 修饰符
    2. Readonly 修饰符
    3. Set Get 访问属性
    4. Static 静态属性
    5. Abstract 抽象类、抽象方法和多态
    6. 可作为接口使用

    TS over JS - 函数(Functions)

                          
                            function fullName(
                              firstName: string,
                              lastName: string,
                              middleInitial?: string): string {
                              return firstName + (middleInitial || '') + lastName
                            }
    
                            fullName('Xiang', 'Gu') // correct
                            fullName('Xiang', 'Gu', 'Gavin') // correct
                          
                        
    1. 参数类型,返回类型(Function Types)
    2. 可选值和默认值(Optional and Default Parameters)
    3. 剩余参数(...展开符)
    4. 函数重载(Overloads)
    5. 箭头函数(自动推断this)

    TS over JS - 泛型(Generics)

                        
                          // call signature of object
                          interface GenericIdentityFn {
                            <T>(arg: T): T;
                          }
                          function identity<T>(arg: T): T {
                              return arg;
                          } 
                          let myIdentity: GenericIdentityFn = identity;
                          // Generic Classes
                          class GenericNumber<T> {
                              zeroValue: T;
                              add: (x: T, y: T) => T;
                          }
                          // Generic Constraints
                          function loggingIdentity<T extends { length: number; }>(arg: T): T {
                              console.log(arg.length);
                              return arg;
                          }
    
                          // Using Class Types in Generics
                          function createInstance<A extends Animal>(c: new () => A) {
                            return new c();
                          }
                        
                      
    1. 泛型(Generic Types)
    2. 泛型类(Generic Classes)
    3. 泛型约束(Generic Constraints)
    4. 在泛型方法中使用类

    TS over JS - 泛型举例

                  
                    createElement <K extends keyof HTMLElementTagNameMap>(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K];
    
                    interface HTMLElementTagNameMap {
                      "a": HTMLAnchorElement;
                      "abbr": HTMLElement;
                      "address": HTMLElement;
                    }
    
                    document.createElement("a") // 这里会推断为HTMLAnchorElement
                  
                

    TS over JS - 声明文件(.d.ts)

                        
                          // .es6.js
                          class Student {
                            constructor(name, age, sex = "male", job) {
                                this.name = name;
                                this.sex = sex;
                                this.job = job;
                                this.fullName =
                                    name.firstName + " " + name.middleInitial + " " + name.lastName;
                                this.age = age;
                            }
                          }
                          // .d.ts
                          declare class Student implements Person {
                            name: MiddleName;
                            sex: "male" | "female";
                            job?: string;
                            fullName: string;
                            age: number;
                            constructor(name: MiddleName, age: number, sex?: "male" | "female", job?: string);
                          }
                          interface Person {
                              name: MiddleName;
                              sex: "male" | "female";
                              age: number;
                          }
                          interface MiddleName extends Name {
                              middleInitial: string;
                          }
                          interface Name {
                              firstName: string;
                              lastName: string;
                          }
                        
                      
    1. 可以通过tsc命令编译ts为对应版本的es+d.ts(angular, antd, mobx)
    2. 可以单独为库文件编写对应的同名.d.ts声明文件(react, vue)
    3. 通过声明合并(Declaration Merging)对已有库进行修改和补充
    4. npm install @types/xxx -D

    Flow v.s TS 真香