javascript 中的型別檢查(2)
我們無需改變 javascript 就可以切實地感受到 typescript 帶來好處,
我們只要 visual studio code 中的 js 檔案頭部加入 //@ts-check,然後在 add 函式第一引數 a 前新增 /* @ type{number} / 我們這時候就將 a 型別定義為 number,如果在呼叫時 add 我們傳入字串型別的引數就會得到相應錯誤提示。
//@ts-check export function add(/**@type{number} */a,b){ return a + b; } add('strng',1); //檢查型別
同樣我們給 printTitle 的引數 title 指定預設值為空字串,這樣也會認為型別為字串,與上面效果相同。
動態語言 VS 靜態語言
動態語言特性
- 靈活性
- less verbose/less ceremony 不拘泥細節和格式
- 更多的改變空間
- 話費在語義上時間會更少
- 容易測試
靜態語言
- 更早進行錯誤檢查和提示
- 更好的編碼文件
- 有優化編譯的條件
- 可以提高執行時的效率
- 更好開發體驗
export function printTitle(title= ''){ console.log(title); } printTitle(123) //提示輸入字串
javascript 和 typescript 可以友好共存
這樣您就可以逐步地改造我們現有的專案,我們可以一個一個的檔案進行轉換為 typescript。
我們有一個簡單的不能再簡單 javascript 檔案,我們現在要將他轉換為 typescript 檔案,只需要將字尾 .js 修改為 .ts 。
const tutorial = { title:'angularjs tutorial', author:'zidea' } class tutorialService{ constructor(apikey){ this.apikey = apikey } } 修改後會提示我們沒有指定 apikey 的型別。

螢幕快照 2019-02-24 下午12.45.33.png
const tutorial = { title:'angularjs tutorial', author:'zidea' } class tutorialService{ private apikey:string constructor(apikey:string){ this.apikey = apikey }
- 我們需要為 apikey 指定型別
- 然後在 class 中定義一個 apikey 字串型別的私有變數
export default class tutorialService{ private apikey:string constructor(apikey:string){ this.apikey = apikey } }
然後讓我們的檔案模組化,export default ,typescript 的編譯器及支援 commonjs
模組管理也支援 es 的模組管理。
export interface ITutorial { title: string, author: string }; export enum NewsSource{ WECHAT = 'we-chat-web', JIANSHU = 'jianshu-web' } export default class tutorialService { private apikey: string; constructor(apikey: string) { this.apikey = apikey; } async feacthArticles(source:NewsSource):Promise<ITutorial[]> { return [{ title:'angular tutorial', author:'zidea' }] } }
- 我們定義介面 ITutorial 來定義 feacthArticles 返回值的型別
- 定義列舉 NewsSource 來限制 NewsSource 的取值範圍
- 然後修改 feacthArticles 函式來確定引數的型別和返回值的型別