TypeScript - 模板字面量型別



模板字串字面量用於在 JavaScript 中建立包含變數的動態字串。類似地,在 TypeScript 中,您可以使用模板字面量型別來建立動態型別,這是在 TypeScript 4.1 版本中引入的。TypeScript 中模板字面量型別的語法與 JavaScript 模板字串字面量非常相似。

語法

您可以按照以下語法在 TypeScript 中使用模板字面量型別。

type type_name = `some_text ${variable_name}`
  • 在上述語法中,“type_name”是型別的名稱。

  • 您需要使用反引號 (``) 來定義模板字面量型別。

  • “some_text”可以是任何將保持不變的字串值。

  • 要在型別中新增任何動態值,您需要在“${}”結構內新增變數名。

示例

讓我們透過一些 TypeScript 示例來詳細瞭解模板字面量型別。

示例:基本用法

在下面的程式碼中,我們定義了“World”型別,其中包含“World”作為值。“Greeting”型別是一個模板字面量型別,其值會根據“World”變數的值而改變。

接下來,我們建立了型別為“Greeting”的“greeting”變數,其中包含“Hello World”值。如果我們嘗試為其分配另一個值,TypeScript 編譯器將丟擲錯誤。

type World = "world";
// Defining a template literal type
type Greeting = `Hello, ${World}`;
const greeting: Greeting = "Hello, world"; // Correct
// const wrongGreeting: Greeting = "Hello, everybody"; // Error: This type is "Hello, world" specifically.
console.log(greeting);

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

const greeting = "Hello, world"; // Correct
// const wrongGreeting: Greeting = "Hello, everybody"; // Error: This type is "Hello, world" specifically.
console.log(greeting);

上面的示例程式碼將產生以下輸出

Hello, world

示例:與聯合型別結合

在此程式碼中,“size”型別包含多個型別值的聯合。“ResponseMessage”型別是一個模板字面量型別,其值會根據“Size”型別的值而改變。

selectSize() 函式採用型別為“Size”的字串作為引數,並返回型別為“ResponseMessage”的值。

接下來,我們透過傳遞“medium”作為函式引數來呼叫該函式。如果我們嘗試傳遞除“small”、“medium”和“large”之外的任何其他字串值作為函式引數,它將丟擲錯誤。

// Creating a type using literal type
type Size = "small" | "medium" | "large";
// Custom template literal type
type ResponseMessage = `${Size} size selected`;

// Function to select size
function selectSize(size: Size): ResponseMessage {
    return `${size} size selected`;
}

// Call the function
const response: ResponseMessage = selectSize("medium"); // "medium size selected"
console.log(response);

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

// Function to select size
function selectSize(size) {
    return `${size} size selected`;
}

// Call the function
const response = selectSize("medium"); // "medium size selected"
console.log(response);

其輸出如下所示

medium size selected

示例:條件字串模式

在此示例中,我們使用了帶有約束的泛型型別。這裡的“T extends Status”表示 T 的值只能來自 status。statusMessage 型別是型別“T”和“status”字串的組合。

printStatus() 函式採用型別 T 作為引數,該引數可以是“Status”型別中的任何一個值,並返回型別為“statusMessage”的值。

接下來,我們透過傳遞“loading”值(它是“Status”型別的一部分)來呼叫 printStatus() 函式。

// Definition of the Status type
type Status = "loading" | "success" | "error";
// T can be any of the values in the Status type
type StatusMessage<T extends Status> = `${T}Status`;

// Function to return a message based on the status
function printStatus<T extends Status>(status: T): StatusMessage<T> {
    return `${status} Status` as StatusMessage<T>;
}

// Call the function with the "loading" status
const loadingMessage = printStatus("Loading"); // "loadingStatus"
console.log(loadingMessage);

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

// Function to return a message based on the status
function printStatus(status) {
    return `${status} Status`;
}

// Call the function with the "loading" status
const loadingMessage = printStatus("Loading"); // "loadingStatus"
console.log(loadingMessage);

其輸出如下所示

Loading Status

示例:API 路由生成

以下示例演示了模板字面量型別的實際應用。

然後,我們定義了 Method 型別,它可以具有 REST API 方法型別中的任何值。Entity 型別定義實體物件。

getRoute() 方法分別採用型別為 Entity 和 Method 的 entity 和 method 作為引數。它在組合 entity 和 method 值後返回型別為 APIRoute 的字串值。

// Defining the Method and Entity types
type Method = "get" | "post" | "delete";
type Entity = "user" | "post";

// Defining the ApiRoute type
type ApiRoute = `/${Entity}/${Method}`;

// Defining the getRoute function
function getRoute(entity: Entity, method: Method): ApiRoute {
    return `/${entity}/${method}` as ApiRoute;
}

// Using the getRoute function
const userRoute = getRoute("user", "post"); // "/user/post"
console.log(userRoute);

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

// Defining the getRoute function
function getRoute(entity, method) {
    return `/${entity}/${method}`;
}

// Using the getRoute function
const userRoute = getRoute("user", "post"); // "/user/post"
console.log(userRoute);

其輸出如下所示

/user/post

在 TypeScript 中,模板字面量型別主要用於需要建立動態型別的情況。

廣告