当前位置: 首页 > news >正文

TypeScript 类型声明

在 TypeScript 开发中简化类型声明,可以通过以下 7 种实用技巧 显著提升效率:


一、善用类型推断(30% 场景免声明)

// ❌ 冗余写法
const user: { name: string; age: number } = { name: 'Jack', age: 25 };

// ✅ 自动推断(hover 变量可见类型)
const user = { name: 'Jack', age: 25 }; 

二、实用类型工具(20% 代码量)

类型工具应用场景示例
Partial<T>所有属性变为可选type Draft = Partial<Article>;
Pick<T, K>选取部分属性type Preview = Pick<Article, 'title'>
Omit<T, K>排除指定属性type SafeUser = Omit<User, 'password'>
ReturnType<T>获取函数返回值类型type Result = ReturnType<typeof fetch>
Record<K, T>快速定义键值类型type Pages = Record<string, React.FC>

三、类型守卫简化逻辑(if 判断即类型)

// 自定义类型守卫
function isAdmin(user: User): user is AdminUser {
  return 'privileges' in user;
}

// 使用示例
const handleUser = (user: User) => {
  if (isAdmin(user)) {
    user.manageSystem(); // 自动识别为 AdminUser 类型
  }
}

四、模块化类型管理

types/
├── user.d.ts        # 用户相关类型
├── api.d.ts         # API 响应类型
└── utils.d.ts       # 工具类型
// user.d.ts
export type UserRole = 'admin' | 'user';

export interface BaseUser {
  id: string;
  name: string;
  role: UserRole;
}

五、泛型优化重复代码

// 通用响应类型
interface ApiResponse<T = unknown> {
  code: number;
  data: T;
  message?: string;
}

// 使用示例
type UserResponse = ApiResponse<User>;
type ListResponse = ApiResponse<User[]>;

六、第三方类型工具库

  1. Zod (运行时类型校验)

    import { z } from "zod";
    
    const UserSchema = z.object({
      name: z.string(),
      age: z.number().positive()
    });
    
    type User = z.infer<typeof UserSchema>; // 自动推断类型
    
  2. TypeFest (高级工具类型)

    import type { CamelCase } from 'type-fest';
    
    type ApiResponse = {
      user_name: string;
      total_count: number;
    };
    
    type FrontendData = {
      [K in keyof ApiResponse as CamelCase<K>]: ApiResponse[K];
    };
    // { userName: string; totalCount: number }
    

七、IDE 高效开发技巧

  1. 快速修复
    在类型错误处按 Ctrl+. 自动生成类型声明

  2. 智能提示
    输入 user. 自动显示所有可用属性和方法

  3. 类型跳转
    Ctrl+Click 跳转到类型定义

  4. 重命名重构
    F2 安全修改类型名称(自动更新所有引用)


八、框架最佳实践

React 组件 Props
// 使用 interface 自动提示
interface ButtonProps {
  variant?: 'primary' | 'secondary';
  children: React.ReactNode;
}

const Button: React.FC<ButtonProps> = ({ variant = 'primary', children }) => (
  <button className={`btn-${variant}`}>{children}</button>
);
Vue Composition API
// 自动推断 ref 类型
const count = ref(0); // Ref<number>
const user = ref<User>(); // Ref<User | undefined>

九、处理第三方库类型

  1. DefinitelyTyped

    npm install --save-dev @types/lodash
    
  2. 框架内置类型

    // Next.js 页面 Props
    import type { GetServerSideProps } from 'next';
    
    export const getServerSideProps: GetServerSideProps = async () => {
      // ...
    }
    

十、终极简化方案

// 使用 satisfies 运算符(TS 4.9+)
const routes = {
  home: '/',
  about: '/about'
} satisfies Record<string, string>;

type Routes = keyof typeof routes; // "home" | "about"

通过结合这些技巧,可使 TypeScript 开发效率提升 50% 以上。核心原则是:让类型系统为你工作,而不是对抗它

相关文章:

  • Kali Linux 2024.4版本全局代理(wide Proxy)配置,适用于浏览器、命令行
  • Pytorch中的ebmedding到底怎么理解?
  • 小皮网站搭建
  • 开源电商项目、物联网项目、销售系统项目和社区团购项目
  • qt-C++笔记之QToolButton和QPushButton的区别
  • 算法1-2 分数线划定
  • Saleae逻辑分析仪的安装与使用
  • 1.2 Scala变量与数据类型
  • Kafka面试题及原理
  • git笔记
  • Java进阶——常用工具类
  • 实例分割 | yolov11训练自己的数据集
  • Mysql 死锁场景及解决方案
  • 图像分类项目2:鸟类图像分类
  • 计算机毕业设计SpringBoot+Vue.js校园失物招领系统(源码+文档+PPT+讲解)
  • 【C】链式二叉树算法题1 -- 单值二叉树
  • 打开 Windows Docker Desktop 出现 Docker Engine Stopped 问题
  • 前缀列表(ip-prefix)配置
  • 10.2 指针进阶_函数指针
  • 2025年上海安卓发展机遇
  • 解放日报:“感觉全世界人都在上海买买买”
  • 中国新闻发言人论坛在京举行,郭嘉昆:让中国声音抢占第一落点
  • 新华时评:博物馆正以可亲可近替代“高冷范儿”
  • 南宁一学校发生伤害案件,警方通报:嫌疑人死亡,2人受伤
  • 中国军网:带你揭开3所新调整组建军队院校的神秘面纱
  • 师爷、文士、畸人:会稽范啸风及其著述