前端TypeScript高级技巧:让你的代码更安全

前端TypeScript高级技巧:让你的代码更安全

毒舌时刻

前端TypeScript?这不是增加工作量吗?

"JavaScript就够了,为什么要用TypeScript"——结果类型错误频发,调试困难,
"TypeScript太严格了,我写起来很麻烦"——结果代码质量差,维护困难,
"我只在关键地方用TypeScript,其他地方用any"——结果失去了TypeScript的意义。

醒醒吧,TypeScript不是负担,而是提高代码质量的利器!

为什么你需要这个?

  • 类型安全:在编译时发现类型错误
  • 代码提示:提供更好的IDE智能提示
  • 重构安全:重构代码时更加安全
  • 可读性:代码更加清晰易懂
  • 可维护性:减少运行时错误,提高代码可维护性

反面教材

// 反面教材:过度使用any function processData(data: any) { // 没有类型检查,容易出错 return data.name.toUpperCase(); } // 反面教材:类型定义不完整 interface User { id: number; name: string; // 缺少email等其他属性 } // 反面教材:类型断言滥用 function getUser(id: number): User { // 不安全的类型断言 return fetch(`/api/users/${id}`).then(res => res.json()) as unknown as User; } 

正确的做法

// 正确的做法:使用泛型 function identity<T>(arg: T): T { return arg; } // 使用泛型约束 interface Lengthwise { length: number; } function loggingIdentity<T extends Lengthwise>(arg: T): T { console.log(arg.length); return arg; } // 正确的做法:使用联合类型和类型守卫 type Shape = Circle | Square; interface Circle { kind: 'circle'; radius: number; } interface Square { kind: 'square'; sideLength: number; } function getArea(shape: Shape): number { // 类型守卫 if (shape.kind === 'circle') { return Math.PI * shape.radius ** 2; } else { return shape.sideLength ** 2; } } // 正确的做法:使用类型推断 const user = { id: 1, name: '张三', email: '[email protected]' }; // TypeScript会自动推断user的类型 // 正确的做法:使用映射类型 interface Person { name: string; age: number; } // 生成只读类型 type ReadonlyPerson = Readonly<Person>; // 生成可选类型 type PartialPerson = Partial<Person>; // 生成必填类型 type RequiredPerson = Required<PartialPerson>; // 正确的做法:使用条件类型 // 提取Promise的返回类型 type UnwrapPromise<T> = T extends Promise<infer U> ? U : T; // 测试 async function fetchData(): Promise<string> { return 'data'; } // 类型会被推断为string let data: UnwrapPromise<ReturnType<typeof fetchData>>; // 正确的做法:使用模板字面量类型 type EventName<T extends string> = `${T}Changed`; type MouseEventName = EventName<'click' | 'mouseover' | 'mouseout'>; // 类型为 'clickChanged' | 'mouseoverChanged' | 'mouseoutChanged' // 正确的做法:使用类型别名和接口 // 类型别名 type UserID = number; type UserName = string; type Email = string; // 接口 interface User { id: UserID; name: UserName; email: Email; createdAt: Date; updatedAt: Date; } // 正确的做法:使用枚举 enum Role { Admin = 'admin', User = 'user', Guest = 'guest' } function checkPermission(role: Role): boolean { return role === Role.Admin; } // 正确的做法:使用命名空间 namespace Validation { export interface StringValidator { isAcceptable(s: string): boolean; } const lettersRegexp = /^[A-Za-z]+$/; const numberRegexp = /^[0-9]+$/; export class LettersOnlyValidator implements StringValidator { isAcceptable(s: 

Read more

VS-CODE 里的github copilot 不支持自己配置模型api

1. 关于配置自定义 Claude API 的支持情况 * 结论:不支持。 * 机制说明: * VS Code 官方 GitHub Copilot 扩展(包括 Agent 功能)强制通过 GitHub 的代理服务器进行鉴权和路由。 * 模型切换:GitHub Copilot 允许在订阅权限范围内切换底层模型(例如从 GPT-4o 切换至 Claude 3.5 Sonnet),但这使用的是 GitHub 的企业/个人订阅配额。 * API Key 限制:无法在官方扩展设置中输入个人的 sk-ant-... (Anthropic API Key) 或自定义 Endpoint。 * 替代方案(非官方扩展): * 若必须使用个人 Claude API

IntelliJ IDEA 接入 AI 编程助手(Copilot、DeepSeek、GPT-4o Mini)

IntelliJ IDEA 接入 AI 编程助手(Copilot、DeepSeek、GPT-4o Mini)

IntelliJ IDEA 接入 AI 编程助手(Copilot、DeepSeek、GPT-4o Mini) 📊 引言 近年来,AI 编程助手已成为开发者的高效工具,它们可以加速代码编写、优化代码结构,并提供智能提示。本文介绍如何在 IntelliJ IDEA 中集成 DeepSeek、GPT-4o Mini、GitHub Copilot,并探索 本地 AI 编程助手 方案,帮助开发者在不同场景下提升编程效率。 👨‍💻 1. GitHub Copilot 集成 Copilot 是由 GitHub 和 OpenAI 推出的 AI 代码补全工具,它可以根据上下文智能生成代码片段。 GitHub Copilot 免费版 vs 付费版对比。 功能免费版付费版代码补全每月

从一句话到一张图:看懂 Stable Diffusion 的“潜空间扩散”生成流程(配图详解)

Stable Diffusion Pipeline Source: Aayush’s Blog, “Stable Diffusion using Hugging Face – Putting everything together” (2022).Used with attribution. 当你输入一句 “A dog wearing a hat(戴帽子的狗)”,模型最后输出一张高清图片。中间到底发生了什么? 这张图展示的,其实就是 Stable Diffusion 这类潜空间扩散模型(Latent Diffusion Model)最核心的工作流:文本 → 语义向量 → 潜空间噪声 → 逐步去噪 → VAE 解码成图像。 本文将按图逐块拆解,并补充它背后的关键概念与工程细节,让你真正理解扩散模型是如何“画画”的。 1. 这张图在讲什么?

【AIGC】如何获取ChatGPT外部GPTs应用的提示词Prompt指令和知识库文件

【AIGC】如何获取ChatGPT外部GPTs应用的提示词Prompt指令和知识库文件

博客主页: [小ᶻ☡꙳ᵃⁱᵍᶜ꙳]本文专栏: AIGC |GPTs应用实例 文章目录 * 💯前言 * 💯获取GPTs的提示词Prompt指令 * 💯获取GPTs的知识库文件 * 💯小结 * 关于GPTs指令如何在ChatGPT上使用,请看这篇文章: 【AIGC】如何在ChatGPT中制作个性化GPTs应用详解     https://blog.ZEEKLOG.net/2201_75539691?type=blog * 关于如何使用国内AI工具复现类似GPTs效果,请看这篇文章: 【AIGC】国内AI工具复现GPTs效果详解     https://blog.ZEEKLOG.net/2201_75539691?type=blog 💯前言 随着 ChatGPT 和其他 AI 应用的不断发展,越来越多的外部 GPTs 被集成进来,以增强其功能和适应多样化的用户需求。这些外部 GPTs 并不仅仅是通用的 聊天助手,而是专为特定场景、