想像一下:您正在愉快地使用 JavaScript 進行編碼,突然出現「無法讀取未定義的屬性『名稱』」。呃,我們都去過那裡! TypeScript 就像有一個朋友,可以在這些錯誤發生之前發現它們。
JavaScript 就像被蜘蛛咬之前的彼得·帕克 - 潛力巨大,但容易發生意外。 TypeScript 是賦予 JavaScript 超能力的蜘蛛咬傷。它添加了一個類型系統,有助於及早發現錯誤並使您的程式碼更加可靠。
讓我們從一個簡單的 JavaScript 函數開始,並將其轉換為 TypeScript:
// JavaScript function greet(name) { return "Hello, " + name + "!"; }
現在,讓我們來補充一些 TypeScript 魔法:
// TypeScript function greet(name: string): string { return "Hello, " + name + "!"; }
看到那個:字串嗎? TypeScript 告訴我們「這個函數接受一個字串並回傳一個字串」。現在試試這個:
greet(123); // Error: Argument of type 'number' is not assignable to parameter of type 'string'
TypeScript 剛剛讓我們避免了潛在的錯誤! ?
讓我們來探索一些基本的 TypeScript 類型:
// Basic types let heroName: string = "Spider-Man"; let age: number = 25; let isAvenger: boolean = true; let powers: string[] = ["web-slinging", "wall-crawling"]; // Object type let hero: { name: string; age: number; powers: string[]; } = { name: "Spider-Man", age: 25, powers: ["web-slinging", "wall-crawling"] };
介面就像是物件的藍圖。它們對於定義資料的形狀非常有用:
interface Hero { name: string; age: number; powers: string[]; catchPhrase?: string; // Optional property } function introduceHero(hero: Hero): void { console.log(`I am ${hero.name}, and I'm ${hero.age} years old!`); if (hero.catchPhrase) { console.log(hero.catchPhrase); } } const spiderMan: Hero = { name: "Spider-Man", age: 25, powers: ["web-slinging", "wall-crawling"] }; introduceHero(spiderMan);
有時您會想建立自己的類型組合:
type PowerLevel = 'rookie' | 'intermediate' | 'expert'; interface Hero { name: string; powerLevel: PowerLevel; } const batman: Hero = { name: "Batman", powerLevel: "expert" // TypeScript will ensure this is one of the allowed values };
泛型就像通配符,讓您的程式碼更可重複使用:
function createHeroTeam<T>(members: T[]): T[] { return [...members]; } interface Superhero { name: string; power: string; } interface Villain { name: string; evilPlan: string; } const heroes = createHeroTeam<Superhero>([ { name: "Iron Man", power: "Technology" }, { name: "Thor", power: "Lightning" } ]); const villains = createHeroTeam<Villain>([ { name: "Thanos", evilPlan: "Collect infinity stones" } ]);
讓我們使用 TypeScript 建立一個簡單的待辦事項應用程式:
interface Todo { id: number; title: string; completed: boolean; dueDate?: Date; } class TodoList { private todos: Todo[] = []; addTodo(title: string, dueDate?: Date): void { const todo: Todo = { id: Date.now(), title, completed: false, dueDate }; this.todos.push(todo); } toggleTodo(id: number): void { const todo = this.todos.find(t => t.id === id); if (todo) { todo.completed = !todo.completed; } } getTodos(): Todo[] { return this.todos; } } // Usage const myTodos = new TodoList(); myTodos.addTodo("Learn TypeScript with baransel.dev"); myTodos.addTodo("Build awesome apps", new Date("2024-10-24"));
TypeScript 和 React 就像花生醬和果凍。這是一個簡單的例子:
interface Props { name: string; age: number; onSuperPower?: () => void; } const HeroCard: React.FC<Props> = ({ name, age, onSuperPower }) => { return ( <div> <h2>{name}</h2> <p>Age: {age}</p> {onSuperPower && ( <button onClick={onSuperPower}> Activate Super Power! </button> )} </div> ); };
// Problem: Object is possibly 'undefined' const user = users.find(u => u.id === 123); console.log(user.name); // Error! // Solution: Optional chaining console.log(user?.name); // Problem: Type assertions const input = document.getElementById('myInput'); // Type: HTMLElement | null const value = input.value; // Error! // Solution: Type assertion or type guard const value = (input as HTMLInputElement).value; // or if (input instanceof HTMLInputElement) { const value = input.value; }
TypeScript 乍看之下似乎是額外的工作,但它就像擁有一種超能力,可以幫助您在錯誤發生之前捕獲它們。從小處開始,逐漸添加更多類型,在您意識到之前,您會想知道沒有它您是如何生活的!
記住:
以上是TypeScript:JavaScript 的超級英雄斗篷的詳細內容。更多資訊請關注PHP中文網其他相關文章!