在当今的前端开发领域,TypeScript 和前端框架已经成为开发者必备的技能。TypeScript 作为 JavaScript 的超集,提供了类型系统,使得代码更加健壮和易于维护。而前端框架,如 React、Vue 和 Angular,则提供了组件化、模块化和高效渲染的解决方案。本文将为你介绍一些实战案例,帮助你从零开始学习 TypeScript 并掌握前端框架。
TypeScript 入门:从基础类型到高级类型
1. TypeScript 基础类型
在 TypeScript 中,基础类型包括数字(number)、字符串(string)、布尔值(boolean)和空值(null、undefined)。以下是一个简单的示例:
let age: number = 25;
let name: string = "张三";
let isStudent: boolean = true;
let ageNull: null = null;
let ageUndefined: undefined = undefined;
2. TypeScript 高级类型
TypeScript 提供了多种高级类型,如接口(interface)、类型别名(type alias)、联合类型(union type)、交叉类型(intersection type)和泛型(generics)。以下是一些高级类型的示例:
// 接口
interface Person {
name: string;
age: number;
}
// 类型别名
type PersonType = {
name: string;
age: number;
};
// 联合类型
let isStudent: "student" | "teacher" | "other" = "student";
// 交叉类型
interface Person {
name: string;
age: number;
}
interface Employee {
id: number;
}
let person: Person & Employee = {
name: "张三",
age: 25,
id: 1
};
// 泛型
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("张三"); // output: string
前端框架实战案例
1. React 实战案例:待办事项列表
React 是一个用于构建用户界面的 JavaScript 库。以下是一个简单的待办事项列表示例:
import React, { useState } from 'react';
function TodoList() {
const [todos, setTodos] = useState<string[]>([]);
const addTodo = (todo: string) => {
setTodos([...todos, todo]);
};
const removeTodo = (index: number) => {
setTodos(todos.filter((_, i) => i !== index));
};
return (
<div>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => removeTodo(index)}>删除</button>
</li>
))}
</ul>
<input type="text" onChange={(e) => addTodo(e.target.value)} />
</div>
);
}
export default TodoList;
2. Vue 实战案例:天气查询
Vue 是一个渐进式 JavaScript 框架。以下是一个简单的天气查询示例:
<template>
<div>
<input v-model="city" placeholder="请输入城市名" />
<button @click="getWeather">查询天气</button>
<div v-if="weather">
<h1>{{ weather.name }} - {{ weather.main.temp }}℃</h1>
<p>{{ weather.weather[0].description }}</p>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const city = ref('');
const weather = ref(null);
const getWeather = async () => {
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city.value}&appid=YOUR_API_KEY`);
const data = await response.json();
weather.value = data;
};
return { city, weather, getWeather };
}
});
</script>
3. Angular 实战案例:图书管理
Angular 是一个基于 TypeScript 的前端框架。以下是一个简单的图书管理示例:
import { Component } from '@angular/core';
@Component({
selector: 'app-book-manager',
template: `
<div>
<input [(ngModel)]="newBook.title" placeholder="请输入书名" />
<input [(ngModel)]="newBook.author" placeholder="请输入作者" />
<button (click)="addBook()">添加图书</button>
<ul>
<li *ngFor="let book of books">{{ book.title }} - {{ book.author }}</li>
</ul>
</div>
`
})
export class BookManagerComponent {
books: { title: string; author: string }[] = [];
newBook: { title: string; author: string } = { title: '', author: '' };
addBook() {
this.books.push({ ...this.newBook });
this.newBook = { title: '', author: '' };
}
}
总结
通过以上实战案例,你可以了解到 TypeScript 和前端框架的基本用法。在实际开发中,你需要不断积累经验,学习更多高级功能和最佳实践。希望这些案例能够帮助你快速入门,成为一名优秀的前端开发者。
