1. 程式人生 > 其它 >新手入門typeScript

新手入門typeScript

強型別與弱型別(型別安全)

  • 強型別不允許隨意的隱士型別轉換,而弱型別是允許的
  • 變數型別允許隨時改變的特點,不是強弱型別的差異

靜態型別與動態型別(型別檢查)

  • 靜態型別:一個變數宣告時它的型別就是明確的,如果聲明後,它的型別就不允許修改。
  • 動態型別:執行階段才能夠明確變數型別,而且變數的型別隨時可以改變。

JavaScript 自有型別系統的問題

  • 任性:缺失了型別系統的可靠性
  • javaScript沒有編譯環節,初期發展就設計成弱型別、動態型別語言
  • 大規模應用下,這種優勢也是劣勢

弱型別的問題

    • 君子約定有隱患,強制要求有保障
  • 強型別的優勢
    • 錯誤更早暴露
    • 程式碼更只能,程式設計更準確
    • 重構更牢靠
    • 減少不必要的型別判斷

Flow靜態型別檢查方案 (工具)

  • 引數-> 型別註解
  • 使用-> yarn add flow-bin --dev
  • flow編譯移除註解-> yarn add flow-remove-types --dev
    • yarn flow-remove-types src -d dist
  • 使用babel代替flow工具
    • yarn add @babel/core @babel/cli @babel/preset-flow --dev
    • 專案中引入.babelrc 檔案{“presets”: ["babel/preset-flow"]}
    • yarn babel src -d dist
  • vscode外掛:flow-language-support 開箱即用
  • flow官網支援的編輯器 https://flow.org/en/docs/editors
  • flow 型別推斷
    • 建議手動新增型別註解
    • 原始型別
      • const a: string = 'aax';
        const b: number = Infinity;
        const c: boolean = false;
        const d: null = null;
        const e: void = undefined;
        const f: symbol = Symbol();
    • 陣列型別
      • const arr1: Array<number> = [1,2,3];
        
        const arr2: number[] 
        = [1,2,3];

        // 元組 陣列長度固定
        const arr3: [string, number] = ['hello', 123]
    • 物件型別
      • const obj1: {foo: String, bar: number} = {foo: 'string', bar: 100}
        
        const obj2: {foo?: String, bar: number} = { bar: 100 }
        
        const obj3: { [string]: string } = {}
        obj3.key1 = 'value1'
        obj3.key2 = 100
    • 函式型別
      • function foo(callback: (string, number) => void) {
          callback(string, 100)
        }
    • 字面量型別
      • const type: 'success' | 'warning' | 'danger' = 'success'
        
        type StringOrNumber = string | number
        
        const b: StringOrNumber = 'string' // 100
        
        const gender: ?number = null // undefined
        
        const gender2: number | null | void = null
    • mixed與any型別
      • 都是指定了任意型別,但是any是弱型別(主要是相容老程式碼用的,實際專案中不建議使用),mixed是強型別。執行階段會非法校驗

型別手冊:https://www.saltycrane.com/cheat-sheets/flow-type/latest/

執行環境API 物件