// 這會觸發類型檢查錯誤 request("GET", "/invalidRoute"); // Error: Argument of type '"/invalidRoute"' is not assignable to parameter of type 'Route'.
相同的概念也可以來動態生成 SQL 查詢語句,同時確保參數的安全性與類型正確性。
1 2 3 4 5 6 7 8 9 10 11
typeTableName = "users" | "posts" | "comments";
functionselectFromTable(table: TableName, id: number): string { return`SELECT * FROM ${table} WHERE id = ${id}`; }
const query = selectFromTable("users", 1); console.log(query); // SELECT * FROM users WHERE id = 1
// 傳入錯誤的表名時,會被 TypeScript 類型檢查發現 selectFromTable("invalidTable", 1); // Error: Argument of type '"invalidTable"' is not assignable to parameter of type 'TableName'.
// 若單位或屬性錯誤,會觸發類型檢查錯誤 applyStyle("background", 10, "px"); // Error: Argument of type '"background"' is not assignable to parameter of type 'CSSProperty'.
constinvalidHandler: EventHandlerName<"click", "button"> = "buttonOnHoverHandler"; // Error: Type '"buttonOnHoverHandler"' is not assignable to type '"buttonOnClickHandler"'.
Azurite Blob service is starting at http://127.0.0.1:10000 Azurite Queue service is starting at http://127.0.0.1:10001 Azurite Table service is starting at http://127.0.0.1:10002