想象一下:您正在愉快地使用 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中文网其他相关文章!