TypeScript - 字面量型別



在 TypeScript 中,字面量型別是基本資料型別的子型別。字面量型別允許您指定變數可以包含的確切值。

TypeScript 中有三種類型的字面量型別。

  • 字串字面量型別

  • 數字字面量型別

  • 布林字面量型別

它們都允許您在變數中儲存特定值,而不是儲存通用的字串、數字或布林值。

語法

您可以遵循以下語法在 TypeScript 中使用字面量型別。

type lit_type = type_1 | type_2 | type_3 | ...

在上述語法中,“type”是建立類型別名的關鍵字。“lit_type”是型別的名稱。“type_1”、“type_2”和“type_3”是字串、布林值或數字型別的數值。

字串字面量型別

字串字面量型別允許您定義一組特定值,變數或函式引數應包含其中的任何值。

示例

在下面的程式碼中,我們建立了“Direction”型別,其中包含字串格式的四個方向。move()函式引數的型別是 Direction,因此它接受四個方向中的任何值。

如果您嘗試傳遞四個方向以外的任何值作為引數,它將丟擲錯誤。

// Defining a custom-type Direction
type Direction = "North" | "East" | "South" | "West";

// Defining a function move that takes a single argument of type Direction.
function move(direction: Direction) {
    console.log(`Moving in the direction: ${direction}`);
}
move("North"); 
move("East"); 
// move("Northeast"); 
// Error: Argument of type '"Northeast"' is not assignable to parameter of type 'Direction'.

編譯後,它將生成以下 JavaScript 程式碼。

// Defining a function move that takes a single argument of type Direction.
function move(direction) {
    console.log(`Moving in the direction: ${direction}`);
}
move("North");
move("East");
// move("Northeast"); 
// Error: Argument of type '"Northeast"' is not assignable to parameter of type 'Direction'.

上述程式碼的輸出如下:

Moving in the direction: North
Moving in the direction: East

數字字面量型別

數字字面量型別類似於字串字面量,但允許您指定確切的數值作為允許的型別。

示例

在下面的程式碼中,“SmallPrimes”型別包含到 11 的小素數作為值。“prime”變數的型別是“SmallPrimes”。因此,它只能包含 2、3、5、7 或 11 中的任何值。

type SmallPrimes = 2 | 3 | 5 | 7 | 11;
let prime: SmallPrimes;
prime = 7; 
console.log(prime); // 7
// prime = 4; 
// Error: Type '4' is not assignable to type 'SmallPrimes'.

編譯後,它將生成以下 JavaScript 程式碼。

let prime;
prime = 7;
console.log(prime); // 7
// prime = 4; 
// Error: Type '4' is not assignable to type 'SmallPrimes'.

上述程式碼的輸出如下:

7

組合字面量型別

您可以使用聯合型別組合不同型別的字面量(字串、數字、布林值),以允許變數儲存一組指定的值。

示例

在下面的程式碼中,“MixedLiterals”型別包含“click”、404 和 true 值。

action 變數可以包含“MixedLiterals”型別三個值中的任何一個值。

// Mixed type literals
type MixedLiterals = "Click" | 404 | true;
let action: MixedLiterals;

action = "Click"; // Valid
console.log(action);

action = 404; // Valid
console.log(action);

action = true; // Valid
console.log(action);
// action = "Other"; 
// Error: Type '"Other"' is not assignable to type 'MixedLiterals'.

編譯後,它將生成以下 JavaScript 程式碼。

let action;
action = "Click"; // Valid
console.log(action);
action = 404; // Valid
console.log(action);
action = true; // Valid
console.log(action);
// action = "Other"; 
// Error: Type '"Other"' is not assignable to type 'MixedLiterals'.

上述程式碼的輸出如下:

Click
404
true

字面量型別的用例

字面量型別有多個用例。但是,我們將研究字面量型別的一些即時用例。

  • 配置 - 用於定義變數或函式引數的特定配置,這些變數或函式引數僅採用特定值。

  • 狀態管理 - 型別字面量可用於狀態管理。

  • API 響應處理 - 用於根據 API 響應狀態處理 API 響應。

TypeScript 中的字面量型別透過允許您指定完全可接受的值來增強應用程式的型別安全性。它還有助於開發人員維護程式碼複雜性並提高可讀性。

廣告