技术文档中心
首页
React
Vue
TypeScript
Kotlin
React Native
Electron
Android
首页
React
Vue
TypeScript
Kotlin
React Native
Electron
Android
  • 基础入门

    • TypeScript 学习指南
    • 基础类型
    • 函数
    • 接口
    • 类
  • 进阶内容

    • 泛型
    • 高级类型
    • 工具类型
    • 装饰器
    • 模块
  • 实战应用

    • 配置文件
    • 实战应用

实战应用

React + TypeScript

函数组件

import React from 'react';

interface Props {
  name: string;
  age?: number;
  onUpdate?: (name: string) => void;
}

const User: React.FC<Props> = ({ name, age, onUpdate }) => {
  return (
    <div>
      <h1>{name}</h1>
      {age && <p>年龄: {age}</p>}
    </div>
  );
};

Hooks

import { useState, useEffect } from 'react';

interface User {
  id: number;
  name: string;
}

function UserList() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    fetchUsers().then(data => {
      setUsers(data);
      setLoading(false);
    });
  }, []);

  return <div>{/* ... */}</div>;
}

事件处理

function Form() {
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value);
  };

  const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    console.log('clicked');
  };

  return <form onSubmit={handleSubmit}>{/* ... */}</form>;
}

Vue + TypeScript

组件定义

import { defineComponent, ref } from 'vue';

export default defineComponent({
  name: 'User',
  props: {
    name: {
      type: String,
      required: true
    },
    age: Number
  },
  setup(props) {
    const count = ref<number>(0);
    
    return {
      count
    };
  }
});

Composition API

import { ref, computed, Ref } from 'vue';

interface User {
  name: string;
  age: number;
}

export function useUser() {
  const user = ref<User | null>(null);
  const isAdult = computed(() => user.value && user.value.age >= 18);

  const fetchUser = async () => {
    const data = await fetch('/api/user').then(r => r.json());
    user.value = data;
  };

  return {
    user,
    isAdult,
    fetchUser
  };
}

Node.js + TypeScript

Express

import express, { Request, Response } from 'express';

const app = express();

interface User {
  id: number;
  name: string;
}

app.get('/users', (req: Request, res: Response) => {
  const users: User[] = [
    { id: 1, name: 'John' }
  ];
  res.json(users);
});

app.listen(3000);

类型定义

// types.ts
export interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
}

export interface User {
  id: number;
  name: string;
  email: string;
}

// api.ts
import { ApiResponse, User } from './types';

async function getUser(id: number): Promise<ApiResponse<User>> {
  const response = await fetch(`/api/users/${id}`);
  return response.json();
}

最佳实践

  1. 启用 strict 模式
  2. 使用接口定义数据结构
  3. 避免使用 any
  4. 合理使用泛型
  5. 类型守卫保证类型安全
  6. 使用工具类型简化代码
最近更新: 2026/2/6 15:39
Contributors: hailong
Prev
配置文件