程式要能發揮作用,我們需要能夠處理一些最基本的資料單位:數字、字串、結構、布林值等。在 TypeScript 中,我們支援與 JavaScript 中預期的相同類型,並新增列舉類型以協助處理。
布林值
最基本的資料類型是簡單的真/假值,JavaScript 和 TypeScript 稱之為 boolean
值。
tsTry
letisDone : boolean = false;
數字
與 JavaScript 相同,TypeScript 中的所有數字都是浮點值或 BigInt 整數。這些浮點數會取得類型 number
,而 BigInt 整數會取得類型 bigint
。除了十六進位和十進位字面值外,TypeScript 也支援 ECMAScript 2015 中引入的二進位和八進位字面值。
tsTry
letdecimal : number = 6;lethex : number = 0xf00d;letbinary : number = 0b1010;letoctal : number = 0o744;letbig : bigint = 100n;
字串
在 JavaScript 中建立網頁程式和伺服器程式的另一個基本部分是處理文字資料。與其他語言相同,我們使用 string
類型來指稱這些文字資料類型。就像 JavaScript 一樣,TypeScript 也使用雙引號 ("
) 或單引號 ('
) 來包圍字串資料。
tsTry
letcolor : string = "blue";color = 'red';
您也可以使用 範本字串,它可以跨越多行並包含內嵌的運算式。這些字串會以反引號/反撇號 (`
) 字元包圍,而內嵌的運算式則為 ${ expr }
的形式。
tsTry
letfullName : string = `Bob Bobbington`;letage : number = 37;letsentence : string = `Hello, my name is ${fullName }.I'll be ${age + 1} years old next month.`;
這等同於以下宣告 sentence
tsTry
letsentence : string ="Hello, my name is " +fullName +".\n\n" +"I'll be " +(age + 1) +" years old next month.";
陣列
TypeScript 和 JavaScript 一樣,允許您使用值陣列。陣列類型可以用兩種方式撰寫。第一種方式是使用元素類型,後面接 []
來表示該元素類型的陣列
tsTry
letlist : number[] = [1, 2, 3];
第二種方式使用一般陣列類型,Array<elemType>
tsTry
letlist :Array <number> = [1, 2, 3];
元組
元組類型允許您表示具有固定數量元素的陣列,其類型已知,但不必相同。例如,您可能希望將值表示為 字串
和 數字
的一對
tsTry
// Declare a tuple typeletx : [string, number];// Initialize itx = ["hello", 10]; // OK// Initialize it incorrectlyType 'number' is not assignable to type 'string'.x = [10 ,"hello" ]; // Error
Type 'string' is not assignable to type 'number'.2322
2322Type 'number' is not assignable to type 'string'.
Type 'string' is not assignable to type 'number'.
存取具有已知索引的元素時,會擷取正確的類型
tsTry
// OKconsole .log (x [0].substring (1));Property 'substring' does not exist on type 'number'.2339Property 'substring' does not exist on type 'number'.console .log (x [1].(1)); substring
存取已知索引集之外的元素會失敗並產生錯誤
tsTry
Tuple type '[string, number]' of length '2' has no element at index '3'.2493Tuple type '[string, number]' of length '2' has no element at index '3'.x [3 ] = "world";Object is possibly 'undefined'.console .log (x [5 ].toString ());
Tuple type '[string, number]' of length '2' has no element at index '5'.2532
2493Object is possibly 'undefined'.
Tuple type '[string, number]' of length '2' has no element at index '5'.
列舉
對 JavaScript 標準資料類型集有用的新增功能是 enum
。與 C# 等語言一樣,列舉是一種為數值值集提供更友善名稱的方法。
tsTry
enumColor {Red ,Green ,Blue ,}letc :Color =Color .Green ;
預設情況下,列舉從 0
開始編號其成員。您可以透過手動設定其其中一個成員的值來變更此設定。例如,我們可以從 1
而不是 0
開始前一個範例
tsTry
enumColor {Red = 1,Green ,Blue ,}letc :Color =Color .Green ;
或者,甚至手動設定列舉中的所有值
tsTry
enumColor {Red = 1,Green = 2,Blue = 4,}letc :Color =Color .Green ;
列舉的一個方便功能是您也可以從數值轉到列舉中該值的對應名稱。例如,如果我們有值 2
,但不知道它對應到上面 Color
列舉中的什麼,我們可以查詢對應的名稱
tsTry
enumColor {Red = 1,Green ,Blue ,}letcolorName : string =Color [2];// Displays 'Green'console .log (colorName );