TypeScript 筆記
此篇更新移至 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, falseobject
:{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
setImplicitAny
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 putstrict
totrue
References
- Coding Tech. (2020). Write Safer JavaScript Applications With TypeScript!. Retrieved from https://youtu.be/t7Us0sWUpRQ (2020)
- Academind. (2020). TypeScript Course for Beginners 2020 — Learn TypeScript from Scratch!. Retrieved from https://youtu.be/BwuLxPH8IDs (2020)
- Simply Explained. (2016). Interfaces (TypeScript tutorial, #6). Retrieved from https://youtu.be/NeUrwZVi4IE (2020)
- The Net Ninja. (2020). TypeScript Tutorial #16 — Interfaces with Classes. Retrieved from https://youtu.be/XPGFqx8Vg-Y (2020)