拓十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

typescript-expert - typescript-cheatsheet

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
返回列表