news 2026/9/26 10:30:57

typescript-expert - typescript-cheatsheet

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
typescript-expert - typescript-cheatsheet

TypeScript 速查表

类型基础

// Primitivesconstname:string='John'constage:number=30constisActive:boolean=trueconstnothing:null=nullconstnotDefined:undefined=undefined// Arraysconstnumbers:number[]=[1,2,3]conststrings:Array<string>=['a','b','c']// Tupleconsttuple:[string,number]=['hello',42]// Objectconstuser:{name:string;age:number}={name:'John',age:30}// Unionconstvalue:string|number='hello'// Literalconstdirection:'up'|'down'|'left'|'right'='up'// Any vs UnknownconstanyValue:any='anything'// ❌ AvoidconstunknownValue:unknown='safe'// ✅ Prefer, requires narrowing

类型别名与接口

// Type AliastypePoint={x:numbery:number}// Interface (preferred for objects)interfaceUser{id:stringname:stringemail?:string// OptionalreadonlycreatedAt:Date// Readonly}// ExtendinginterfaceAdminextendsUser{permissions:string[]}// IntersectiontypeAdminUser=User&{permissions:string[]}

泛型

// Generic functionfunctionidentity<T>(value:T):T{returnvalue}// Generic with constraintfunctiongetLength<Textends{length:number}>(item:T):number{returnitem.length}// Generic interfaceinterfaceApiResponse<T>{data:Tstatus:numbermessage:string}// Generic with defaulttypeContainer<T=string>={value:T}// Multiple genericsfunctionmerge<T,U>(obj1:T,obj2:U):T&U{return{...obj1,...obj2}}

工具类型

interfaceUser{id:stringname:stringemail:stringage:number}// Partial - all optionaltypePartialUser=Partial<User>// Required - all requiredtypeRequiredUser=Required<User>// Readonly - all readonlytypeReadonlyUser=Readonly<User>// Pick - select propertiestypeUserName=Pick<User,'id'|'name'>// Omit - exclude propertiestypeUserWithoutEmail=Omit<User,'email'>// Record - key-value maptypeUserMap=Record<string,User>// Extract - extract from uniontypeStringOrNumber=string|number|booleantypeOnlyStrings=Extract<StringOrNumber,string>// Exclude - exclude from uniontypeNotString=Exclude<StringOrNumber,string>// NonNullable - remove null/undefinedtypeMaybeString=string|null|undefinedtypeDefinitelyString=NonNullable<MaybeString>// ReturnType - get function return typefunctiongetUser(){return{name:'John'}}typeUserReturn=ReturnType<typeofgetUser>// Parameters - get function parameterstypeGetUserParams=Parameters<typeofgetUser>// Awaited - unwrap PromisetypeResolvedUser=Awaited<Promise<User>>

条件类型

// Basic conditionaltypeIsString<T>=Textendsstring?true:false// Infer keywordtypeUnwrapPromise<T>=TextendsPromise<inferU>?U:T// Distributive conditionaltypeToArray<T>=Textendsany?T[]:nevertypeResult=ToArray<string|number>// string[] | number[]// NonDistributivetypeToArrayNonDist<T>=[T]extends[any]?T[]:never

模板字面量类型

typeColor='red'|'green'|'blue'typeSize='small'|'medium'|'large'// CombinetypeColorSize=`${Color}-${Size}`// 'red-small' | 'red-medium' | 'red-large' | ...// Event handlerstypeEventName='click'|'focus'|'blur'typeEventHandler=`on${Capitalize<EventName>}`// 'onClick' | 'onFocus' | 'onBlur'

映射类型

// Basic mapped typetypeOptional<T>={[KinkeyofT]?:T[K]}// With key remappingtypeGetters<T>={[KinkeyofTas`get${Capitalize<string&K>}`]:()=>T[K]}// Filter keystypeOnlyStrings<T>={[KinkeyofTasT[K]extendsstring?K:never]:T[K]}

类型守卫

// typeof guardfunctionprocess(value:string|number){if(typeofvalue==='string'){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('fly'inanimal){animal.fly()}else{animal.swim()}}// Custom type guardfunctionisString(value:unknown):valueisstring{returntypeofvalue==='string'}// Assertion functionfunctionassertIsString(value:unknown):assertsvalueisstring{if(typeofvalue!=='string'){thrownewError('Not a string')}}

可辨识联合(Discriminated Unions)

// With type discriminanttypeSuccess<T>={type:'success';data:T}typeError={type:'error';message:string}typeLoading={type:'loading'}typeState<T>=Success<T>|Error|Loadingfunctionhandle<T>(state:State<T>){switch(state.type){case'success':returnstate.data// Tcase'error':returnstate.message// stringcase'loading':returnnull}}// Exhaustive checkfunctionassertNever(value:never):never{thrownewError(`Unexpected value:${value}`)}

品牌类型(Branded Types)

// Create branded typetypeBrand<K,T>=K&{__brand:T}typeUserId=Brand<string,'UserId'>typeOrderId=Brand<string,'OrderId'>// Constructor functionsfunctioncreateUserId(id:string):UserId{returnidasUserId}functioncreateOrderId(id:string):OrderId{returnidasOrderId}// Usage - prevents mixingfunctiongetOrder(orderId:OrderId,userId:UserId){}constuserId=createUserId('user-123')constorderId=createOrderId('order-456')getOrder(orderId,userId)// ✅ OK// getOrder(userId, orderId) // ❌ Error - types don't match

模块声明

// Declare module for untyped packagedeclaremodule'untyped-package'{exportfunctiondoSomething():voidexportconstvalue:string}// Augment existing moduledeclaremodule'express'{interfaceRequest{user?:{id:string}}}// Declare globaldeclareglobal{interfaceWindow{myGlobal:string}}

TSConfig 要点

{"compilerOptions":{// Strictness"strict":true,"noUncheckedIndexedAccess":true,"noImplicitOverride":true,// Modules"module":"ESNext","moduleResolution":"bundler","esModuleInterop":true,// Output"target":"ES2022","lib":["ES2022","DOM"],// Performance"skipLibCheck":true,"incremental":true,// Paths"baseUrl":".","paths":{"@/*":["./src/*"]}}}

最佳实践

// ✅ Prefer interface for objectsinterfaceUser{name:string}// ✅ Use const assertionsconstroutes=['home','about']asconst// ✅ Use satisfies for validationconstconfig={api:'https://api.example.com'}satisfies Record<string,string>// ✅ Use unknown over anyfunctionparse(input:unknown){if(typeofinput==='string'){returnJSON.parse(input)}}// ✅ Explicit return types for public APIsexportfunctiongetUser(id:string):User|null{// ...}// ❌ Avoidconstdata:any=fetchData()data.anything.goes.wrong// No type safety
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/26 10:29:18

五子棋AI自博弈推理加速116倍:C++与GPU优化实战

1. 从一局五子棋说起&#xff1a;为什么要死磕推理速度五子棋这东西&#xff0c;规则简单到用一张餐巾纸就能讲明白&#xff0c;但真要让 AI 通过自博弈把棋力练出来&#xff0c;计算量一点都不“简单”。我最初用 Python 写了个能跑的自博弈框架&#xff0c;逻辑上没毛病&…

作者头像 李华
网站建设 2026/9/26 10:29:14

OpenResearch实践指南:打造可复现、可协作的研究工作流

OpenResearch 这个词&#xff0c;最近在研究工具圈子里出镜率越来越高。有人把它理解成开放获取的学术运动&#xff0c;也有人拿它当标签&#xff0c;统称那些把文献、实验、笔记和发布流程全部开源的个人研究项目。我自己把这套思路折腾了大半年&#xff0c;从一个“把论文 PD…

作者头像 李华
网站建设 2026/9/26 10:29:01

ChatGPT Work 还是 Codex?需求、文档、代码三类任务的入口决策表

ChatGPT Work 还是 Codex?需求、文档、代码三类任务的入口决策表 [!NOTE] ChatGPT Work 与 Codex 不是简单的“一个写文档、一个写代码”,真正的分界在交付物、所需工具、执行环境和验收证据。 Work 更适合从目标出发组织多来源材料并形成可审阅成果;Codex 更适合进入代码库…

作者头像 李华
网站建设 2026/9/26 10:28:38

ax:面向智能体的Kubernetes原生调度范式

1. “ax”不是缩写&#xff0c;是新一代智能体调度范式的代号最近在技术社区和开源项目讨论里频繁刷到“ax”&#xff0c;尤其和Kubernetes、agentic、orchestration这些词绑在一起出现——它既不是某个被遗忘的Linux命令&#xff0c;也不是Chrome插件名&#xff0c;更不是Goog…

作者头像 李华
网站建设 2026/9/26 10:25:53

RS485远距离通信与NB-IoT上传协同设计实战

1. 这不是普通串口通信&#xff1a;BC65 R7KA8T2LFLCAC 组合的真实定位与价值边界你手头有一块智能电表&#xff0c;它通过RS485接口输出计量数据&#xff1b;旁边还有一组温湿度、电流谐波、漏电流传感器&#xff0c;同样走RS485总线。传统做法是拉一根双绞线&#xff0c;接个…

作者头像 李华