Typescript 1 - basic

跟上次的文章比起來已經很久沒有更新了XD,這次正好算自己回顧一下曾經寫typescript的一些心得吧,另外這系列的文章比較會在於實務上的操作,新手級別的介紹(初入JS的新手們),就麻煩先行去找 mdn 等相關的網站學一下囉。

有寫過javascript的通常都會遇到trace code的時候,到處串api/events/option然後沒有文件,只好在每個點下console.log去查到底會出現什麼。這時候如果改成使用typescript的話,就可以很輕鬆的解決掉這些問題。只要定義好型別,做好pass value的架構,typescript可以協助輕鬆import/restructure/type hint,也是因為這些的好處,讓我越來越不能接受沒有type hint的情況了XD
有興趣的可以看一下playground會被compile成什麼樣子
以下就先簡單介紹下typescript常用的一些宣告方式,先用常見的來說明
let str: string;
let num: number;
如果是以object來進行宣告的話
let foo: {
    bar: string;// foo.bar是string type
}
這樣在傳值的時候foo就只能接受{bar: string}裡面的bar被限制為string type
如果是Array的話
let arr: string[] = ['hello', 'world']
這樣的arr就只能接受string型別的資料輸入
此外實務使用上亦有string literalnumeric literal兩種型別

let str: 'foo' | 'bar';

let dice: 1 | 2 | 3 | 4 | 5 | 6;
如此一來str僅能接受foobar的文字,而dice同樣只能接受1~6的數字輸入
另外typescript亦有提供enum的型別(只有在typescript可以使用到)
至於enum是什麼呢?
查wiki大概解釋中文=>列舉...XD
enum其實不會很難,想成是自定義的狀態就行,像是設計switch結構的時候
switch (state) {
    case 'foo':
        return 'foo';
    case 'bar':
        return 'bar';
}
這個時候,大家都知道state裡面可以接受foobar,但是在使用的時候會因為傳值上的不明確,需要不停的重複查要傳入的文字。
而我在進行這類的設計上,最簡單的處理方式就是設定constant string,讓我可以進行調用
const SampleState = {
    FOO: 'foo',
    BAR: 'bar',
}
// 使用上
const state = SampleState.FOO;
switch(state) {
    case SampleState.FOO:
        return 'foo'
    case SampleState.BAR:
        return 'bar'
}
而在typescript則是將其化成可讀性更高的enum型別
enum SampleState {
    FOO,
    BAR
}

const state:SampleState = SampleState.FOO; // SampleState就可以當成type囉
switch(state) {
    case SampleState.FOO:
        return 'foo'
    case SampleState.BAR:
        return 'bar'
}
我可以清楚的知道,switch接受的傳值有哪些,而這個也會在typescript中強制定義只能使用SampleState的東西,如果名稱設計的清楚,翻查文件的機率就降低了。
當然typescript除了有強型別的定義外,它還是提供讓人偷懶的方式any
let obj:any
不過問題就會是失去了strong type的優勢,也無法知道obj到底傳來什麼東西,所以慎用。
第一章先這樣,後續會講interface使用上的事情

留言

這個網誌中的熱門文章

ts-node 應用

ubuntu 日常(X)紀錄

Angular 2 with Third Party files