TypeScript 筆記

TypeScript notes

R4 Cheng
2 min readDec 10, 2020

此篇更新移至 https://github.com/chengr4/all-about-JS/tree/main/all-about-TS

  • A language building up on JavaScript
  • Can not be executed by JS environments like the browser

Content:

+ 常用指令

+ Core types (核心宣告)

+ Something in tsconfig.json

+ How to migrate JS to TS?

+ Reference

常用指令

tsc --init // 初始化 project
tsc -w // Dynamically compile to JS in whole project

Core types (核心宣告)

  • number: 1, 5.3, -10 … (所有數都是這個宣告,沒有 int or float)
  • string: “hi”, ‘Hi’, `hi`
  • boolean: true, false
  • object: {age:40}
  • array: [1, 2, 3]
let favoriteActivities: string[]; // E.g. string only array
  • tuple (TS only, == fixed length-array)
let role: [number, string] = [2, 'author'];
  • enum (TS only)

使用時機:只有固定幾個選擇的時候

enum Role { ADMIN, READ_ONLY, AUTHOR }
// With identifier
enum Role { ADMIN = 5, READ_ONLY = 100, AUTHOR = 201}
  • union (TS only)

使用 |

  • Literal type
  • function
  • unknown (稍微比 any 嚴格)
  • interface (TS only)

Someting in tsconfig.json

  • "sourceMap”: Helpful for debugging
  • "outDir”: 設置被 compile 的 JS 的位址
  • "noEmitOnError": true: 如果有任何錯誤將無法 compile to JS

How to migrate JS to TS?

警告: 我沒實際操作過!

1. Just make it work

  • Generate a tsconfig.json file with TS
  • In tsconfig.json set ImplicitAny to false
  • Rename all .js files to .ts/.tsx

2. Be explicit

  • No implicit ANY
  • Add common known types
  • Add typings for 3rd party tools (?

3. Be strict

注意:將會產生很多問題

  • Go to tsconfig.json and put strict to true

References

--

--

R4 Cheng
R4 Cheng

Written by R4 Cheng

「0」が過去で「1」が未来「今」は何処にもない

No responses yet