电子商务网站建设的风险分析,哪些公司网站做的很好,wordpress网站监测,d8 wordpress前端TypeScript开发指南#xff1a;从入门到精通
什么是TypeScript#xff1f;
TypeScript是微软开发的一种开源编程语言#xff0c;它是JavaScript的超集#xff0c;为JavaScript添加了静态类型检查。TypeScript最终会被编译成纯JavaScript#xff0c;可以在任何支持Java…前端TypeScript开发指南从入门到精通什么是TypeScriptTypeScript是微软开发的一种开源编程语言它是JavaScript的超集为JavaScript添加了静态类型检查。TypeScript最终会被编译成纯JavaScript可以在任何支持JavaScript的环境中运行。为什么选择TypeScript静态类型检查在编译阶段就能发现类型错误提高代码质量增强的IDE支持更好的代码补全、导航和重构功能代码可读性类型定义使代码更易于理解和维护大型项目友好适合中大型项目的开发基础类型系统1. 基础类型// 布尔类型letisActive:booleantrue;lethasError:booleanfalse;// 数字类型letcount:number42;letprice:number99.99;// 字符串类型letusername:stringJohn Doe;letmessage:stringHello,${username};// 数组类型letnumbers:number[][1,2,3,4,5];letnames:Arraystring[Alice,Bob,Charlie];// 元组类型固定长度的数组letperson:[string,number][John,25];2. 枚举类型enumStatus{PENDINGpending,IN_PROGRESSin_progress,COMPLETEDcompleted,FAILEDfailed}letcurrentStatus:StatusStatus.PENDING;enumPriority{LOW1,MEDIUM,HIGH,URGENT}3. 任意类型letdynamicValue:any可以是任何类型;dynamicValue123;dynamicValuetrue;dynamicValue{name:Object};// 未知类型比any更安全letunknownValue:unknownsome value;if(typeofunknownValuestring){console.log(unknownValue.toUpperCase());// 安全使用}接口和类型别名1. 接口定义interfaceUser{id:number;name:string;email:string;age?:number;// 可选属性readonlycreatedAt:Date;// 只读属性}interfaceAdminextendsUser{role:admin|super_admin;permissions:string[];}// 实现接口classUserManagerimplementsUser{id:number;name:string;email:string;readonlycreatedAt:Date;constructor(userData:User){this.iduserData.id;this.nameuserData.name;this.emailuserData.email;this.createdAtnewDate();}}2. 类型别名// 基本类型别名typeIDnumber|string;typeCallback()void;typeResultT{success:boolean;data?:T;error?:string;};// 联合类型typeStatusCode200|201|400|404|500;typeHTTPResponse{status:StatusCode;data:any;};// 交叉类型typePerson{name:string;};typeEmployee{employeeId:number;};typePersonEmployeePersonEmployee;函数类型1. 函数参数和返回值// 基本函数类型functiongreet(name:string):string{returnHello,${name}!;}// 可选参数functioncalculateArea(width:number,height?:number):number{returnheight?width*height:width*width;}// 默认参数functionwithDefault(value:stringdefault):string{returnvalue;}// 剩余参数functionsum(...numbers:number[]):number{returnnumbers.reduce((total,num)totalnum,0);}2. 函数类型表达式// 函数类型typeEventHandler(event:MouseEvent)void;typeFilterFunctionT(item:T)boolean;// 函数作为参数functionprocessArrayT(items:T[],filter:FilterFunctionT):T[]{returnitems.filter(filter);}constnumbers[1,2,3,4,5,6];constevenNumbersprocessArray(numbers,(num)num%20);泛型1. 泛型函数// 基本泛型functionidentityT(arg:T):T{returnarg;}conststringResultidentitystring(hello);constnumberResultidentitynumber(42);// 泛型约束functionlogLengthTextends{length:number}(item:T):T{console.log(item.length);returnitem;}2. 泛型接口和类// 泛型接口interfaceRepositoryT{create(item:T):T;findById(id:number):T|null;update(id:number,item:PartialT):T|null;delete(id:number):boolean;}interfaceUser{id:number;name:string;}classUserRepositoryimplementsRepositoryUser{privateusers:User[][];create(user:User):User{this.users.push(user);returnuser;}findById(id:number):User|null{returnthis.users.find(useruser.idid)||null;}update(id:number,userUpdate:PartialUser):User|null{constuserthis.findById(id);if(user){Object.assign(user,userUpdate);}returnuser;}delete(id:number):boolean{constindexthis.users.findIndex(useruser.idid);if(index!-1){this.users.splice(index,1);returntrue;}returnfalse;}}类和继承1. 类的定义classVehicle{// 属性protectedbrand:string;privatemodel:string;publicyear:number;// 构造函数constructor(brand:string,model:string,year:number){this.brandbrand;this.modelmodel;this.yearyear;}// 方法publicgetInfo():string{return${this.year}${this.brand}${this.model};}// getter和settergetmodelName():string{returnthis.model;}setmodelName(value:string){this.modelvalue;}// 静态方法staticcompare(vehicle1:Vehicle,vehicle2:Vehicle):number{returnvehicle1.year-vehicle2.year;}}// 继承classCarextendsVehicle{privatedoors:number;constructor(brand:string,model:string,year:number,doors:number){super(brand,model,year);this.doorsdoors;}publicgetInfo():string{return${super.getInfo()}-${this.doors}doors;}// 访问父类protected属性publicgetBrand():string{returnthis.brand;}}constcarnewCar(Tesla,Model 3,2023,4);console.log(car.getInfo());2. 抽象类abstractclassShape{abstractcalculateArea():number;publicdisplayInfo():void{console.log(Area:${this.calculateArea()});}}classRectangleextendsShape{constructor(privatewidth:number,privateheight:number){super();}calculateArea():number{returnthis.width*this.height;}}classCircleextendsShape{constructor(privateradius:number){super();}calculateArea():number{returnMath.PI*this.radius**2;}}装饰器Decorators1. 类装饰器functionComponent(options:{selector:string;template:string}){returnfunction(constructor:Function){constructor.prototype.selectoroptions.selector;constructor.prototype.templateoptions.template;constructor.prototype.renderfunction(){console.log(Rendering:${options.template});};};}Component({selector:#app,template:divHello World/div})classAppComponent{render(){console.log(Component rendered);}}constappnewAppComponent();app.render();实际应用示例1. React组件importReactfromreact;interfaceButtonProps{variant:primary|secondary|danger;size:small|medium|large;children:React.ReactNode;onClick?:()void;disabled?:boolean;}constButton:React.FCButtonProps({variant,size,children,onClick,disabled}){constbaseClassbtn;constvariantClassbtn-${variant};constsizeClassbtn-${size};return(button className{${baseClass}${variantClass}${sizeClass}}onClick{onClick}disabled{disabled}{children}/button);};exportdefaultButton;2. API服务interfaceApiResponseT{data:T;status:number;message:string;}interfaceUser{id:number;name:string;email:string;}classApiService{privatebaseUrlhttps://api.example.com;asyncgetT(endpoint:string):PromiseApiResponseT{constresponseawaitfetch(${this.baseUrl}${endpoint});if(!response.ok){thrownewError(HTTP error! status:${response.status});}returnresponse.json();}asyncpostT,U(endpoint:string,data:U):PromiseApiResponseT{constresponseawaitfetch(${this.baseUrl}${endpoint},{method:POST,headers:{Content-Type:application/json,},body:JSON.stringify(data),});if(!response.ok){thrownewError(HTTP error! status:${response.status});}returnresponse.json();}}constapiServicenewApiService();// 使用示例asyncfunctionloadUsers():PromiseUser[]{constresponseawaitapiService.getUser[](/users);returnresponse.data;}asyncfunctioncreateUser(userData:OmitUser,id):PromiseUser{constresponseawaitapiService.postUser,typeofuserData(/users,userData);returnresponse.data;}3. 状态管理// 简化的状态管理示例typeActionT|{type:SET_STATE;payload:T}|{type:RESET};interfaceStoreT{state:T;dispatch:(action:ActionT)void;subscribe:(listener:()void)()void;}functioncreateStoreT(initialState:T):StoreT{letcurrentStateinitialState;constlistenersnewSet()void();return{state:currentState,dispatch(action:ActionT){switch(action.type){caseSET_STATE:currentStateaction.payload;break;caseRESET:currentStateinitialState;break;}listeners.forEach(listenerlistener());},subscribe(listener){listeners.add(listener);return()listeners.delete(listener);}};}// 使用示例interfaceCounterState{count:number;}constcounterStorecreateStoreCounterState({count:0});counterStore.dispatch({type:SET_STATE,payload:{count:10}});constunsubscribecounterStore.subscribe((){console.log(State changed:,counterStore.state);});counterStore.dispatch({type:SET_STATE,payload:{count:20}});unsubscribe();最佳实践1. 类型命名约定接口使用PascalCase通常不加前缀如UserService而不是IUserService类型别名使用PascalCase枚举使用PascalCase私有属性使用下划线前缀或camelCase2. 常见陷阱// ❌ 避免使用anyfunctionbadFunction(data:any):any{returndata.property;// 没有类型检查}// ✅ 好的做法functiongoodFunctionTextendsobject(data:T):T{returndata;// 类型安全}// ❌ 避免any数组letbadArray:any[][];// ✅ 好的做法letgoodArray:number[][];// ❌ 避免类型断言过度使用letvalue:unknownhello;letstr:stringvalueasstring;// 可能有风险// ✅ 更好的做法letstr:stringtypeofvaluestring?value:;3. 配置建议// tsconfig.json{compilerOptions:{target:ES2020,module:ESNext,strict:true,esModuleInterop:true,skipLibCheck:true,forceConsistentCasingInFileNames:true,moduleResolution:node,resolveJsonModule:true,declaration:true,declarationMap:true,sourceMap:true},include:[src/**/*],exclude:[node_modules,dist]}总结TypeScript为前端开发带来了强大的类型系统帮助我们构建更可靠、可维护的应用程序。通过掌握基础类型系统接口和类型别名函数类型泛型类和继承装饰器实际应用模式你可以显著提升代码质量减少运行时错误并改善开发体验。TypeScript不是障碍而是帮助你写出更好代码的工具。