TypeScript 的數據類型

TypeScript 的數據類型

本文將解釋 TypeScript 中的數據類型。

YouTube Video

TypeScript 的數據類型

TypeScript 提供了多種數據類型。這使您可以為變數、函數參數和返回值定義嚴格的類型。以下是主要的數據類型及其用法。

基本型別

number 類型

1let age: number = 25;
2console.log(age);          // Outputs: 25
3console.log(typeof age);    // Outputs: number
  • number 是用於處理數值的類型,包括整數和浮點數(小數)。處理超過某些限制的數值會導致 InfinityNaN(非數值)。
1// Decimal calculations
2console.log(0.1 + 0.2 === 0.3); // false
3console.log(0.1 + 0.2); // 0.30000000000000004
4
5// Calculations with large numbers
6console.log(9007199254740991 + 1); // correct value
7console.log(9007199254740991 + 2); // incorrect value
  • 在 TypeScript 中,數字是以浮點數形式表示的。這可能會導致計算結果出現輕微的不精確。

  • 當需要進行精確計算時,例如金融金額,必須避免這樣的捨入誤差。例如,您可以使用 BigInttoFixed(),或者使用像 decimal.js 這樣的庫來調整小數位。

string 類型

string 類型用於處理文本數據。

1let greeting: string = "Hello, TypeScript!";
2console.log(greeting);     // Outputs: Hello, TypeScript!
3console.log(typeof greeting);  // Outputs: string

boolean(邏輯類型)

boolean 類型有兩個值:truefalse

1let isOpen: boolean = true;
2console.log(isOpen);       // Outputs: true
3console.log(typeof isOpen);    // Outputs: boolean

null 和 undefined

null 表示“不存在的值”,undefined 表示“未定義的值”。

1let emptyValue: null = null;
2let notDefined: undefined = undefined;
3
4console.log(emptyValue);       // Outputs: null
5console.log(typeof emptyValue);    // Outputs: object (JavaScript specification)
6
7console.log(notDefined);       // Outputs: undefined
8console.log(typeof notDefined);    // Outputs: undefined

Array

在 TypeScript 中,您可以指定數組元素的類型。number[] 是數字數組,string[] 是字符串數組。

1let numbers: number[] = [1, 2, 3, 4];
2console.log(numbers);        // Outputs: [1, 2, 3, 4]
3console.log(typeof numbers); // Outputs: object
4
5let words: string[] = ["TypeScript", "JavaScript"];
6console.log(words);          // Outputs: ["TypeScript", "JavaScript"]
7console.log(typeof words);   // Outputs: object

元組(Tuple)

元組是包含不同類型元素的數組。

1let person: [string, number] = ["Alice", 30];
2console.log(person);         // Outputs: ["Alice", 30]
3console.log(typeof person);  // Outputs: object

枚舉(Enum)

enum 定義了一組具名常量。

1enum Color {
2    Red,
3    Green,
4    Blue
5}
6
7let favoriteColor: Color = Color.Green;
8console.log(favoriteColor);  // Outputs: 1 (Defaults start from 0)
9console.log(typeof favoriteColor); // Outputs: number

any

any 類型可以包含任意類型的值,用於您希望禁用類型檢查時。

1let anything: any = "Hello";
2console.log(anything);       // Outputs: Hello
3console.log(typeof anything);    // Outputs: string
4
5anything = 42;
6console.log(anything);       // Outputs: 42
7console.log(typeof anything);    // Outputs: number

聯合類型(Union Type)

使用聯合類型,您可以定義可以容納多種類型之一的變量。

1let identifier: number | string = "ID_12345";
2console.log(identifier);     // Outputs: ID_12345
3console.log(typeof identifier);  // Outputs: string
4
5identifier = 12345;
6console.log(identifier);     // Outputs: 12345
7console.log(typeof identifier);  // Outputs: number

總結

  • numberstringboolean:原始類型。
  • nullundefined:特殊值。
  • 數組 (Array):具有類型註解的數組。
  • Tuple:包含不同類型元素的陣列。
  • 枚舉 (enum):一種列舉類型。
  • any:任意類型。
  • 聯合 (Union):一個可以擁有多種類型值的變量。

透過使用這些數據類型,TypeScript 增強了類型安全性,使開發過程中更容易避免錯誤。

封裝對象

TypeScript 中的 包裝物件(Wrapper Objects) 是自動創建的物件,用來將基本數據類型視為物件。基本類型允許輕量且快速的操作,而物件類型具有方法和屬性,可實現更豐富的操作。

在 JavaScript(和 TypeScript)中,對應於基本類型(如 stringnumberboolean)的包裝物件存在。它們分別使用名為 StringNumberBoolean 的建構函數創建。

以下是包裝物件的示例。

字串物件(String Object)

String 物件為字串提供屬性和方法。

1let strPrimitive: string = "Hello, World!";
2let strObject: String = new String("Hello, World!");
3
4console.log(strPrimitive);         // Outputs: Hello, World!
5console.log(typeof strPrimitive);  // Outputs: string
6
7console.log(strObject);            // Outputs: [String: 'Hello, World!']
8console.log(typeof strObject);     // Outputs: object

特點:

  • 與基本類型的 string 不同,String 物件被 typeof 視為 object
  • 在操作字串或調用字串方法時,包裝物件非常有用。

數字物件(Number Object)

Number 物件為數字提供屬性和方法。

1let numPrimitive: number = 42;
2let numObject: Number = new Number(42);
3
4console.log(numPrimitive);         // Outputs: 42
5console.log(typeof numPrimitive);  // Outputs: number
6
7console.log(numObject);            // Outputs: [Number: 42]
8console.log(typeof numObject);     // Outputs: object

特點:

  • Number 物件作為數字的包裝物件,包含用於數值操作的方法(如 toFixed)。

布林物件(Boolean Object)

Boolean 物件為布林值提供屬性和方法。

1let boolPrimitive: boolean = true;
2let boolObject: Boolean = new Boolean(true);
3
4console.log(boolPrimitive);        // Outputs: true
5console.log(typeof boolPrimitive); // Outputs: boolean
6
7console.log(boolObject);           // Outputs: [Boolean: true]
8console.log(typeof boolObject);    // Outputs: object

特點:

  • Boolean 物件是基本類型 boolean 的包裝物件,並被視為 object

包裝物件與基本類型的差異

由於包裝物件被視為物件,性能略有下降,但因為增加了屬性和方法,可以進行更多的功能操作。此外,使用 ===== 進行比較時存在差異。

1let numPrimitive: number = 123;
2let numObject: Number = new Number(123);
3
4console.log('==  : ', numPrimitive == numObject);  // Outputs: true (Value comparison)
5console.log('=== : ', numPrimitive === numObject); // Outputs: false (Due to differing types)

特點:

  • == 比較值,而 === 進行包括類型在內的嚴格比較。=== 在比較包裝對象(Wrapper Objects)與原始類型時會返回 false

類型轉換

在 TypeScript 中,正確管理 隱式顯式類型轉換 是很重要的。

隱式類型轉換

  • 在 TypeScript 中,應盡可能避免隱式類型轉換以確保類型安全。
1const result: string = 5 + "5"; // "55" (the number is converted to a string)
2
3console.log(result);
  • 在這個例子中,數字 5 被隱式轉換為字符串,結果是字符串 "55"

顯式類型轉換

  • 在 TypeScript 中,使用類型註解或類型轉換函數來安全地執行類型轉換。
1const num: string = "123";
2const convertedNum: number = Number(num); // Converts "123" to the number 123
3
4console.log(typeof num);
5console.log(typeof convertedNum);
  • 在這個例子中,使用 Number() 函數將字符串 "123" 明確地轉換成數字 123

類型檢查

在 TypeScript 中,您可以使用 typeof 運算符來檢查變量的數據類型。

 1// Output: The type of 42 is: number
 2console.log('The type of 42             is:', typeof 42);
 3
 4// Output: The type of 42 is: bigint
 5console.log('The type of 42n            is:', typeof 42n);
 6
 7// Output: The type of "hello" is: string
 8console.log('The type of "hello"        is:', typeof "hello");
 9
10// Output: The type of true is: boolean
11console.log('The type of true           is:', typeof true);
12
13// Output: The type of undefined is: undefined
14console.log('The type of undefined      is:', typeof undefined);
15
16// Output: The type of null is: object
17console.log('The type of null           is:', typeof null);
18
19// Output: The type of Symbol() is: symbol
20console.log('The type of Symbol()       is:', typeof Symbol());
21
22// Output: The type of {} is: object
23console.log('The type of {}             is:', typeof {});
24
25// Output: The type of function () {} is: function
26console.log('The type of function () {} is:', typeof function () {});
  • 在 TypeScript 中,您可以使用 typeof 來檢查類型,但若需要更精確的類型檢查,也建議使用 instanceofis 運算符。

總結

  • 包裝對象(Wrapper Objects) 被視為對象,因為它們為原始類型提供了額外的方法和屬性。
  • StringNumberBoolean 是包裝對象的代表性例子。
  • 與原始類型不同,包裝對象通過 typeof 被識別為 object

您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。

YouTube Video