Typescript學習筆記

爲何使用Typescript?

微軟推出TypeScript主要是爲實現兩個目標:javascript

  • 爲Javascript提供可選的類型系統;
  • 兼容當前及將來的JavaScript的特性。

靜態類型帶來的好處:java

  • 有利於代碼重構,它在編譯器編譯的時候就能捕獲錯誤。
  • 類型明確有利於閱讀。

JavaScript常見語法

TypeScript是JavaScript的「超集」,typescript將javascript語法標準化。node

typescript.jpeg

  1. == 與 ===webpack

    使用==進行比較時,會進行隱式轉換。git

    2 == 2 true
    2 == '2' true
    2 === '2' false
  2. 引用es6

    除字面量外,JavaScript中的任何對象(包括函數、數組、正則表達式等)都是一個引用。github

  3. null和undefinedweb

    變量沒有初始化:undefined。變量不可用爲null。正則表達式

    undefined == undefined true
    undefined == null true
    // 檢查變量是否初始化
    if( typeof val !== 'undefined'){}
  4. thistypescript

    this關鍵字指向調用上下文

    function foo(){console.log(this)} /** this --> window **/
    var obj = {foo:function(){console.log(this)}} 
    obj.foo() /** this --> obj */
  5. 閉包

    內部函數訪問外部變量,此時外部函數的變量被內部函數綁定,稱爲閉包。

    function outer(){
      var outerVal = '1'
      function inner(){
        console.log(outerVal)
      }
      outer()
    }
    /** inner 綁定了 outerVal */
  6. 數字

    JavaScript中數值是雙精度的64位的number

    console.log(.1 + .2) // 0.30000000000000004

內置整數類型限制 Number.MAX_SAFE_INTEGER-Number.MIN_SAFE_INTEGER

金融計算中通常使用 big.js

NaN,計算出的結果不是合法數值時返回NaN,檢測NaN,Number.isNaN。

  1. thuthy

thuthy.jpeg

!!雙感嘆號,第一個!是將值轉爲布爾值,第二個邏輯反轉。

ES6語法

  1. class

    /*ES6*/
    class Point {
      x: number
      y: number
      constructor(x: number, y: number) {
        this.x = x
        this.y = y
      }
      add(point: Point) {
        return new Point(this.x + point.x, this.y + point.y)
      }
    }
    
    /*編譯後ES5*/
    var point = function(){
      function Point(x, y){
        this.x = x;
        this.y = y;
      }
      Point.prototype.add = function(point){
       return  new Point(this.x + point.x, this.y + point.y)
      }
      return Point;
    }()

繼承

/*ES6*/
class Point3D extends Point {
  z: number
  constructor(x: number, y: number, z: number) {
    super(x, y)
    this.z = z
  }
  add(point: Point3D) {
    var point2D = super.add(point)
    return new Point3D(this.x + point2D.x, this.y + point2D.y, this.z + point.z)
  }
}

/*編譯後ES5*/
var point3D = function(_super){
  __extends(Point3D, _super)
  function Point3D(x, y, z){
    _super.call(this, x, y)
    this.z = z;
  }
  Point3D.prototype.add = function(point){
     var point2D = _super.prototype.add.call(this, point)
   return new Point3D(this.x + point2D.x, this.y + point2D.y, this.z + point.z)
  }
  return Point;
}(Point)

/**__extends typescript 編譯 extends 時生成*/
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
/*
d表示派生類,b表示基類
*/
  return function (d, b) {
        extendStatics(d, b); // 拷貝靜態變量
        function __() { this.constructor = d; } // 保留派生構造器
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); //d.prototype.__proto__ = b.prototype
    };
})();

區分 proto prototype

javascript 中全部對象都有屬性__ proto __

/** 查找屬性順序 
obj.property
obj.__proto__.property
obj.__proto__.__proto__.property
**/

javasript 全部的函數都有屬性 prototype,prototype有個指向函數自己的構造器constructor。

function Foo(){
  this.name = "xm"
}
var foo = new Foo();
/**經過函數建立的對象,會將函數prototype傳給對象__proto__*/
console.log(foo.__proto__ === Foo.prototype)
  1. 箭頭函數

    var inc = x => x + 1;

箭頭函數帶來語法簡潔和this丟失問題。

  1. rest參數

    ...+參數名的形式表示最後一個參數,獲取時轉爲數組。

  2. let和const

    var 變量是函數做用域,let 變量塊做用域

    /**閉包中的var*/
    var funcs = []
    for(var i = 0;i < 3; i++){
      funcs.push(function(){
        console.log(i)
      })
    }
    for(var j = 0;j < 3; j++){
      funcs[j]();
    }
    /*輸出 3*/

const 聲明常量值。

  1. 解構

    支持對象和數組解構。

    /*對象解構*/
    var person = {name:'x',age:12,gender:1}
    var {name, age} = person
    console.log(name, age) // x, 12
    var {x, y, ...remaining} = {x: 1, y: 2, z: 4, w: 5} // 看做刪除了x,y
    console.log(x,y,remaining) // 1,2 {z:4,w:5}
  2. 擴展運算符

    Function.prototype.apply

    /*apply調用*/
    function foo(x,y){}
    var args = [0,1]
    foo.apply(null, args)
    // 新語法
    foo(...args)
    // 數組追加元素
    var list = [1, 2]
    list = [...list, 3] //  [1,2,3]
    list = [0,...list,4] // [0,1,2,3,4]
  3. for...of

    /*for...in*/
    for(var e in [7,8,9]){console.log(e) }// 返回索引
    for(var e of [7,8,9]){console.log(e) }// 返回元素
  4. Promise

    使用Promise處理異步和回調函數。

    var promise = new Promise((resolve, reject) => {resolve()//回調正確值
                                                   reject() // 異常值
                                                   })
    promise.then(res => {}) // 正常
    .catch(err => {}) // 異常

並行流程控制,Promise.all([promise1,promise2]).then(res => [result1, result2])

  1. generators

    function* idGen(){
        let index = 0
        while(index < 3) yield /*暫停*/ index++;
    }
    var id = idGen();
    console.log(id.next());
    console.log(id.next());
    console.log(id.next());
    console.log(id.next());
  2. async/await

    async function foo(){
        var result = await exPromise() //等待promise執行返回
        console.log(result)
    }

TS項目構成

  1. 編譯上下文

    tsconfig.json配置文件,配置選項:tsconfig

  2. 聲明空間

    類型聲明空間和變量聲明空間。

    • 類 (class): 類型, .
    • 接口 (interface): 類型.
    • 枚舉 (enum): 類型, .
    • 類別名 (type): 類型.
    • 函數 (function): .
    • 變量 (let, const, var, parameters): .
  3. 模塊

    默認狀況下聲明處於全局命名空間中。使用export變成文件模塊。

    模塊路徑查找

    /**相對路徑**/
    import * as foo from './foo' // 同級目錄
    import * as foo from '../foo' // 上級目錄
    import * as foo from '../someFolder/foo // 相對目錄
    
    /**導入路徑不是相對路徑時,動態查找**/
    import * as foo from 'foo'
    /*
    查找順序
    ./node_modules/foo
    ../node_modules/foo
    ../../node_modules/foo
    */
    import * as foo from 'something/foo'
    /**
    ./node_modules/something/foo
    ../node_modules/something/foo
    ../../node_modules/something/foo
    */
    /* place */
    import * as foo from 'foo'
    /**查找順序*/
    /**
    foo 是文件 foo.ts
    foo 是目錄 foo/index.ts
    foo 是目錄 foo/package.json 有 types
    foo 是目錄 foo/package.json 有 main
    **/
  4. 命名空間

    //typescript 聲明
    namespace Utility {
      export function log(msg) {
        console.log(msg);
      }
      export function error(msg) {
        console.log(msg);
      }
    }
    // usage
    Utility.log('Call me');
    Utility.error('maybe');
var Utility;
(function (Utility) {
    function log(msg) {
        console.log(msg);
    }
    Utility.log = log;
    function error(msg) {
        console.log(msg);
    }
    Utility.error = error;
})(Utility || (Utility = {}));
// usage
Utility.log('Call me');
Utility.error('maybe');
  1. 動態導入表達式

    // 動態加載
    import(/* webpackChunkName: "momentjs" */ 'moment')
      .then(moment => {
        // 懶加載的模塊擁有全部的類型,而且可以定期工做
        const time = moment().format();
        console.log('TypeScript >= 2.4.0 Dynamic Import Expression:');
        console.log(time);
      })
      .catch(err => {
        console.log('Failed to load moment', err);
      });

建立TS項目

  1. 安裝node環境,建立目錄進入執行 npm init -y;
  2. 安裝ts npm install typescript --save-dev ;
  3. 建立文件 node.d.ts npm install @types/node --save-dev;
  4. 初始化tsconfig.json npx tsc --init --rootDir src --outDir lib --esModuleInterop --resolveJsonModule --lib es6 , dom --module commonjs;
  5. 添加ts-node:npm install ts-node --save-dev 實現實時編譯和運行;
  6. 添加nodemon:npm install nodemon --save-dev,只要文件被改變,它就會調用ts-node。

TS類型系統

  1. 基本概念

    基本類型 number string boolean string[]

    接口 interface

    特殊類型 any、null、undefined和void

    // 接口
    interface Name{
        first: string,
        last: string
    };
    let n : Name;
    n = {
        first: 'Li',
        last:'p'
    }
    // 泛型
    function contact<T>(items : T[]): T[]{
        //......
        return items;
    }
    // 聯合類型
    function join(items : string[] | string){
        //......
    }
    // 交叉類型
    function extend<T, U>(first: T, last : U) :T & U{
        const result = <T & U>{}
        return result
    }
    // 元祖類型
    let nameNum : [string, number]
    //類型別名
    type mind = string | Number
    let m : mind
  2. @types

    倉庫 @types 經過配置tsconfig.json的compilerOptions.types控制全局。

  3. 環境聲明

    使用關鍵字declare進行聲明,通常放在.d.ts文件。

  4. 枚舉

    數字枚舉和字符串枚舉。

  5. lib.d.ts

    安裝TypeScript時,會順帶安裝一個lib.d.ts聲明文件。這個文件包含JavaScript運行時及DOM(Document Object Model,文檔對象模型)中存在的各類常見的JavaScript環境聲明。

  6. 函數

    聲明函數 type inc = (num : number) => number

  7. 可調用可實例化

    // 可調用
    interface ReturnStr{
     () : string;
    }
    declare const foo : ReturnStr
    const str = foo() // str 字符串
    // 內聯註解
    const overload: {
     (foo: string): string;
     (foo: number): number;
    } = (foo: any) => foo
    // 可實例化
    interface NewAble {
     new (): string;
    }
    declare const newAble: NewAble;
    const foo = new newAble
  1. 類型斷言

    Ts能夠以任何方式去重寫其推斷和分析的類型,稱爲類型斷言。

    interface Foo{
      Bar : string
    }
    const f1 = {} as Foo;
    f1.bar = "1";
    const f2 = <Foo>{};
    f2.bar = "2";
  1. Freshness

    檢查字面量類型

    function hasName(some: { name: string }) {
      some.name = "name"; // 正確
      some.age = 12; // 錯誤
    }
  1. 類型保護

    typeof (typeof x === 'string')

    instanceof (foo instanceof Foo)

    in 檢查對象是否存在對應屬性

  2. readonly

    type Foo = {
      readonly bar: string;
    };
    const f: Foo = { bar: "x" };
    f.bar = "y"; // 錯誤,不可修改
  1. 泛型

    類的實例成員、類的方法、函數的參數、函數返回值之間的約束。

  2. never

    never類型就是TypeScript中的底部類型。用於一個總會拋出錯誤的函數或一個總會拋出錯誤的函數。

    never與void的差別,void表示沒有任何類型,never表示永遠不存在的值的類型。

  3. 異常處理

    try {
      throw new Error("err.");
    } catch (error) {
      console.log(error)
    }

代碼風格約定

  1. 使用camelCase形式爲變量和函數命名。
  2. 使用PascalCase形式爲類命名。
  3. 使用PascalCase形式爲接口命名。
  4. 類型別名使用PascalCase形式進行命名。
  5. 命名空間使用PascalCase形式進行命名。
  6. 枚舉類型使用PascalCase形式進行命名。
  7. 對於須要明確代表不可用的狀況,null和undefined都不建議使用。
  8. 格式化

    tsfmt命令格式化,使用單引號,空格兩tab,若是想用extends或implements,則建議使用interface。

TS編譯原理

.....待續再看

相關文章
相關標籤/搜索