首页/新闻资讯/正文详情

typescript-expert - typescript-cheatsheet

发布时间:2026/9/26 10:30:58 来源:云帆数科 栏目:资讯中心
typescript-expert - typescript-cheatsheet
TypeScript 速查表类型基础// Primitivesconstname:stringJohnconstage:number30constisActive:booleantrueconstnothing:nullnullconstnotDefined:undefinedundefined// Arraysconstnumbers:number[][1,2,3]conststrings:Arraystring[a,b,c]// Tupleconsttuple:[string,number][hello,42]// Objectconstuser:{name:string;age:number}{name:John,age:30}// Unionconstvalue:string|numberhello// Literalconstdirection:up|down|left|rightup// Any vs UnknownconstanyValue:anyanything// ❌ AvoidconstunknownValue:unknownsafe// ✅ Prefer, requires narrowing类型别名与接口// Type AliastypePoint{x:numbery:number}// Interface (preferred for objects)interfaceUser{id:stringname:stringemail?:string// OptionalreadonlycreatedAt:Date// Readonly}// ExtendinginterfaceAdminextendsUser{permissions:string[]}// IntersectiontypeAdminUserUser{permissions:string[]}泛型// Generic functionfunctionidentityT(value:T):T{returnvalue}// Generic with constraintfunctiongetLengthTextends{length:number}(item:T):number{returnitem.length}// Generic interfaceinterfaceApiResponseT{data:Tstatus:numbermessage:string}// Generic with defaulttypeContainerTstring{value:T}// Multiple genericsfunctionmergeT,U(obj1:T,obj2:U):TU{return{...obj1,...obj2}}工具类型interfaceUser{id:stringname:stringemail:stringage:number}// Partial - all optionaltypePartialUserPartialUser// Required - all requiredtypeRequiredUserRequiredUser// Readonly - all readonlytypeReadonlyUserReadonlyUser// Pick - select propertiestypeUserNamePickUser,id|name// Omit - exclude propertiestypeUserWithoutEmailOmitUser,email// Record - key-value maptypeUserMapRecordstring,User// Extract - extract from uniontypeStringOrNumberstring|number|booleantypeOnlyStringsExtractStringOrNumber,string// Exclude - exclude from uniontypeNotStringExcludeStringOrNumber,string// NonNullable - remove null/undefinedtypeMaybeStringstring|null|undefinedtypeDefinitelyStringNonNullableMaybeString// ReturnType - get function return typefunctiongetUser(){return{name:John}}typeUserReturnReturnTypetypeofgetUser// Parameters - get function parameterstypeGetUserParamsParameterstypeofgetUser// Awaited - unwrap PromisetypeResolvedUserAwaitedPromiseUser条件类型// Basic conditionaltypeIsStringTTextendsstring?true:false// Infer keywordtypeUnwrapPromiseTTextendsPromiseinferU?U:T// Distributive conditionaltypeToArrayTTextendsany?T[]:nevertypeResultToArraystring|number// string[] | number[]// NonDistributivetypeToArrayNonDistT[T]extends[any]?T[]:never模板字面量类型typeColorred|green|bluetypeSizesmall|medium|large// CombinetypeColorSize${Color}-${Size}// red-small | red-medium | red-large | ...// Event handlerstypeEventNameclick|focus|blurtypeEventHandleron${CapitalizeEventName}// onClick | onFocus | onBlur映射类型// Basic mapped typetypeOptionalT{[KinkeyofT]?:T[K]}// With key remappingtypeGettersT{[KinkeyofTasget${CapitalizestringK}]:()T[K]}// Filter keystypeOnlyStringsT{[KinkeyofTasT[K]extendsstring?K:never]:T[K]}类型守卫// typeof guardfunctionprocess(value:string|number){if(typeofvaluestring){returnvalue.toUpperCase()// string}returnvalue.toFixed(2)// number}// instanceof guardclassDog{bark(){}}classCat{meow(){}}functionmakeSound(animal:Dog|Cat){if(animalinstanceofDog){animal.bark()}else{animal.meow()}}// in guardinterfaceBird{fly():void}interfaceFish{swim():void}functionmove(animal:Bird|Fish){if(flyinanimal){animal.fly()}else{animal.swim()}}// Custom type guardfunctionisString(value:unknown):valueisstring{returntypeofvaluestring}// Assertion functionfunctionassertIsString(value:unknown):assertsvalueisstring{if(typeofvalue!string){thrownewError(Not a string)}}可辨识联合Discriminated Unions// With type discriminanttypeSuccessT{type:success;data:T}typeError{type:error;message:string}typeLoading{type:loading}typeStateTSuccessT|Error|LoadingfunctionhandleT(state:StateT){switch(state.type){casesuccess:returnstate.data// Tcaseerror:returnstate.message// stringcaseloading:returnnull}}// Exhaustive checkfunctionassertNever(value:never):never{thrownewError(Unexpected value:${value})}品牌类型Branded Types// Create branded typetypeBrandK,TK{__brand:T}typeUserIdBrandstring,UserIdtypeOrderIdBrandstring,OrderId// Constructor functionsfunctioncreateUserId(id:string):UserId{returnidasUserId}functioncreateOrderId(id:string):OrderId{returnidasOrderId}// Usage - prevents mixingfunctiongetOrder(orderId:OrderId,userId:UserId){}constuserIdcreateUserId(user-123)constorderIdcreateOrderId(order-456)getOrder(orderId,userId)// ✅ OK// getOrder(userId, orderId) // ❌ Error - types dont match模块声明// Declare module for untyped packagedeclaremoduleuntyped-package{exportfunctiondoSomething():voidexportconstvalue:string}// Augment existing moduledeclaremoduleexpress{interfaceRequest{user?:{id:string}}}// Declare globaldeclareglobal{interfaceWindow{myGlobal:string}}TSConfig 要点{compilerOptions:{// Strictnessstrict:true,noUncheckedIndexedAccess:true,noImplicitOverride:true,// Modulesmodule:ESNext,moduleResolution:bundler,esModuleInterop:true,// Outputtarget:ES2022,lib:[ES2022,DOM],// PerformanceskipLibCheck:true,incremental:true,// PathsbaseUrl:.,paths:{/*:[./src/*]}}}最佳实践// ✅ Prefer interface for objectsinterfaceUser{name:string}// ✅ Use const assertionsconstroutes[home,about]asconst// ✅ Use satisfies for validationconstconfig{api:https://api.example.com}satisfies Recordstring,string// ✅ Use unknown over anyfunctionparse(input:unknown){if(typeofinputstring){returnJSON.parse(input)}}// ✅ Explicit return types for public APIsexportfunctiongetUser(id:string):User|null{// ...}// ❌ Avoidconstdata:anyfetchData()data.anything.goes.wrong// No type safety

相关推荐

基于深度学习的旅游路线规划系统的设计大数据分析项目案例机器学习算法
基于深度学习的旅游路线规划系统的设计大数据分析项目案例机器学习算法

1.1 课题背景与意义近年来,随着人们生活水平提高和旅游业快速发展,个性化旅游需求日益增长。传统旅游规划方式主要依赖人工查询和攻略分享,存在信息分散、规划效率低、推荐内容同质化等问题。尤其对于自由行游客,如何在海量旅游信… · 2026/9/26 10:30:58

YOLOv8鸡蛋识别数据集实战:从标注格式到训练避坑全指南
YOLOv8鸡蛋识别数据集实战:从标注格式到训练避坑全指南

简介:面向目标检测与YOLOv8实战人群的鸡蛋识别数据集,包含已标注的鸡蛋图像及对应标签文件,平均正确识别率可达98.9%,可直接用于训练、验证与性能对比,适合目标检测初学者和农业视觉项目开发者。压缩包共2000个文件&am… · 2026/9/26 10:30:52

AI Agent平台从0到1搭建实战:造一个能干活的数字同事
AI Agent平台从0到1搭建实战:造一个能干活的数字同事

最近总有朋友问我:AI Agent 到底是不是又一轮概念炒作?我的答案很直接——不是,而且我自己已经在用 Agent 干活了。这篇内容,就是把我从零搭建 AI Agent 平台的过程、踩过的坑、想明白的道理,完整复盘一遍。标题叫“人… · 2026/9/26 10:30:52

数智码力:Python字符串处理大全!日常文本操作一键搞定
数智码力:Python字符串处理大全!日常文本操作一键搞定

文本处理属于最频繁出现的实践应用场景之一, 在日常办公活动里进行文字整理、数据清理、内容解析以及批量修改文件内容等事务时, 都是无法离开字符串操作环节的。很多初学者在面对文本处理工作场合,仅仅能够使用基础的拼接和切片方法, 一旦遭遇复杂的替换、分割、去除空格、格式… · 2026/9/26 11:08:11

我的编程学习启程 | 第一篇博客
我的编程学习启程 | 第一篇博客

大家好,这是我的第一篇技术博客,很高兴在这里记录我的编程成长之路。自我介绍我是一名计算机相关专业的学生,目前正在学习C语言,初步接触程序逻辑、基础语法。在学习过程中,我感受到代码解决问题的能力,也发… · 2026/9/26 11:08:11

Java 排序算法详细教学:从冒泡排序到快速排序
Java 排序算法详细教学:从冒泡排序到快速排序

1. 为什么需要掌握排序算法排序是程序开发中最常见的基础操作之一。无论是给商品列表按价格排序、给用户按注册时间排序,还是给搜索结果按相关度排序,背后都离不开排序算法。对于 Java 开发者来说,掌握排序算法不仅能帮助你理解 Arrays.sort … · 2026/9/26 11:08:11

省下千元订阅费!用 TaoToken 统一 Key 给 Cline 配置自主任务 AI 智能体,codex 平替实测
省下千元订阅费!用 TaoToken 统一 Key 给 Cline 配置自主任务 AI 智能体,codex 平替实测

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/26 11:08:11

C++代码实现MATLAB中的d2c函数功能
C++代码实现MATLAB中的d2c函数功能

// d2c.cpp // 完全自包含的 MATLAB d2c (ZOH) 实现 // 编译: g -stdc17 -O2 d2c.cpp -o d2c#include <iostream> #include <iomanip> #include <complex> #include <vector> #include <cmath> #include <stdexcept> #include <string&… · 2026/9/26 11:08:11

Atlas 300V部署YOLOv5全指南:从模型转换到性能调优
Atlas 300V部署YOLOv5全指南:从模型转换到性能调优

最近在做一个边缘AI推理项目&#xff0c;客户指定要在Atlas平台上跑YOLOv5目标检测&#xff0c;整个过程中从选型、部署到调优踩了不少坑。今天把整个项目完整拆一遍&#xff0c;从Atlas 300V 24G这块卡到底是不是运算加速卡开始&#xff0c;到最终YOLO模型成功上卡推理&#x… · 2026/9/26 11:08:04

数据库课后习题答案别硬背:当测试用例集刷,效率翻倍
数据库课后习题答案别硬背:当测试用例集刷,效率翻倍

简介&#xff1a;万常选版《数据库原理与设计》课后习题答案资源&#xff0c;覆盖第2至6章及第9章&#xff0c;适合正在学习关系模型、数据库建模、关系数据理论与模式求精的本科生、自学者作为复习与自测材料。压缩包共7个文件&#xff0c;含3个doc参考答案、2个sql示例脚本、… · 2026/9/26 0:00:21

OpenClaw 替代品?Hermes Agent 踩坑实录:macOS 飞书接入 TaoToken 配置
OpenClaw 替代品?Hermes Agent 踩坑实录:macOS 飞书接入 TaoToken 配置

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/26 0:00:40

向下兼容与向上兼容:接口设计中的兼容性策略与工程实践
向下兼容与向上兼容:接口设计中的兼容性策略与工程实践

一次版本升级事故&#xff0c;是很多团队绕不过去的坎。线上环境里&#xff0c;服务端明明已经上线了新版接口&#xff0c;老的移动端还在照着旧文档传参数。请求一到网关&#xff0c;校验直接拒绝&#xff0c;用户操作失败&#xff0c;客服群炸了锅&#xff0c;开发群里开始互… · 2026/9/26 0:00:46

了解更多?预约专属演示

我们的顾问将为您一对一讲解产品与方案

企业微信二维码