# TypeScript 筆記 [TOC] ###### tags: `typescript` # TypeScript 安裝 ```shell= ## 安裝 typescript的指令工具 ## 記得 -g ,要讓該工具可在任何地方使用 $ npm install -g typescript ## 初始化 TS 編譯器設定檔 ## then 會蹦出 tsconfig.json 檔案 $ tsc --init ## 新增一個名為 test.ts 檔案 ## 接下來,在同一個檔案資料夾下輸入指令 $ tsc ## TypeScript 編譯器就會幫我們自動掃描所有 .ts 結尾的檔案並且產出 JS 檔案 ## then 可以使用 NodeJS 在後端執行編譯過後的 JS 檔案 $ node test.js ``` # Type Annotation 型別註記 ## 型別註記的目的 - 除了是讓開發者明確知道變數固定在哪個型別外,TypeScript 也能協助我們確保不會做錯事情 (它不用猜就知道要怎麼幫我們關注該變數) - [TypeScript 筆記:原始型別](https://simonallen.coderbridge.io/2021/08/09/primitive-type/) ## 如何註記 - 使用 `:` ```typescript= const fruit: string = 'Apple'; // 冒號後面接型別方式定義 ``` - 使用 `=>` - 這裡指的是 TypeScript 的 `=>` 而非 ES6 `=>` 的箭頭函 - typeScript 的 `=>` 通常用在函式表達式上 ```typescript= let test = function (a: number, b: number): number { return a * b; }; // 目前 test 變數的型別,是由型別推論推測而來 ``` 龜毛一點... ```typescript= let test: (a: number, b: number) => number = function (a: number, b: number): number { return a * b; }; // 變數與賦予的值都進行了註記,看似很嚴謹但也增加了閱讀上的困難 ``` :::danger `any` 這種 type 是造成型別混亂的根源,typescript 裡會無法監督 ::: ## Delayed Initialization 延遲初始 - 先定義變數後,不直接指派值,而是當程式碼執行到後面才開始指派 - 該變數會無條件被視為 `any` 型別 - 為了避免有 `any` 型別的狀態發生,應當對這些被指派 Nullable Types 的變數或者不立即被指派值的變數做型別註記 ## 具有型別但是預設為“空”值或 Nullable Types - 未確定變數被正式丟入合法的值之前的這段空間,不能使用該變數 - 需要特別使用 `union` 將該變數註記為 `<YOUR-TYPE> | <nullable-type>` 的格式 ```typescript= var test: string | null = null; // 讓變數除了可以成為 string外,也可以成為 Nullable Type test = 'Hello'; test = null; test = 'Hello again'; ``` > 建議:除非可以直接指派值,否則初始化時,就指派 Nullable Type 的值 # Assertion 斷言 - 型別斷言只能用在 Expression 表達式上 - 因為 Expression 表達式會返回值,斷言會覆蓋編譯器對該值的型別推論 ## Assertion 的寫法 ```typescript= 值 as 型別 ``` ```typescript= // 第三方函式 getName(),預期會回傳字串 const name = getName() as string ``` # Annotation註記與 Assertion斷言的差異 - 型別註記大多用在宣告階段(變數、物件與函式..等等),規範其內容型別 - 型別斷言只能用在 Expression 表達式上 - 型別斷言會覆蓋型別推論的結果告訴編譯器,開發者預期限制的型別為何 # Reference - [讓 TypeScript 成為你全端開發的 ACE!](https://ithelp.ithome.com.tw/users/20120614/ironman/2685) - [TypeScript 筆記:推斷、註記與斷言](https://simonallen.coderbridge.io/2021/08/06/ts-inference-annotations-assertiong/)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up