问题与实战你觉得使用TS有什么好处?1.1Ts是JS的增强版。它为JS添加了可选的静态类型和基于类的面向对象编程,并扩展了JS语法。TS的功能比JS多。1.2TS是一种面向对象的编程语言,包括类和接口的概念1.3TS在开发阶段可以给出编译错误,而JS只能在运行时暴露1.4是强类型语言,可以清楚的知道各种数据types,代码可读性很强,几乎每个人都很快明白1.5TS中有很多方便的特性,比如optionalchaining//optionchainconstobj=response;if(obj&&obj.aa&&obj.aa.bb){//...}if(obj?.aa?.bb){//...}类型和接口有什么异同?使用接口描述数据结构,使用类型描述类型2.1都支持描述一个对象或函数接口User{name:string;年龄:数字;}typeUser={name=string;年龄=人数;}2.2都允许扩展typeName={name:string;}interfaceUserextendsName{}2.3只有type能做的事type可以申请基本类型别名、联合类型、祖先等类型typeName=string;接口狗{wong();}界面猫{miao();}类型Pet=Dog|猫;typePetList=[Dog,Cat]在已有类型的基础上,如何扩展一个大部分相似但部分不同的类型?选择OmitinterfaceTest{name:string;性别:数量;高度:字符串;}typeSex=Pick//确保Sex总是数字consta:Sex={性别:1};输入WithoutSex=Omit;constb:WithoutSex={name:'cxx',height:'xxxx'};通过泛型!!!什么是泛型?泛型的具体使用?泛型是指在定义函数、接口或类时不预先指定具体类型,然后在使用时指定类型的特性。interfaceTest{userId:T}typeTestA=Test;//{userId:string}typeTestB=Test;//{userId:number}使用装饰器实现一个计算函数运行时间逻辑导出函数measure(target:any,name:any,descriptor:any){constoldValue=descriptor.value;descriptor.value=asyncfunction(){conststart=Date.now();constres=awaitoldValue.apply(this,arguments);console.log(`${name}执行时间${Date.now()-start}`);返回资源;}返回描述符;}缓存装饰器constcacheMap=newMap();导出函数测量(目标:任何,名称:任何,描述符:任何){constoldValue=descriptor.value;descriptor.value=asyncfunction(...args:any){//函数名+参数保证缓存key的唯一性constcacheKey=name+JSON.stringfiy(参数);if(!cacheMap.get(cacheKey)){//Promise.resolve强制将val执行结果包装成promise//报错catch时,清空缓存。下次,重新执行constcacheValue=Promise.resolve(val.apply(this,arg).catch(()=>cacheMap.set(cacheKey,null)));cacheMap.set(cacheKey,cacheValue)}returncacheMap.get(cacheKey)}返回描述符;}通过TS约束参数实现一个路由跳转,routerHelper//router/index.tsexportenumRouterPath{Index='/',About='/about',User='/user',}//routerHelperimport{Dictionary}来自'vue-router/types/router';从'../router'导入路由器,{RoutePath};导出类型BaseRouteType=Dictionary;导出接口IndexParam扩展BaseRouteType{名称:字符串;}exportinterfaceAboutParamextendsBaseRouteType{testName:string;}exportinterfaceUserParamextendsBaseRouteType{userId:string;}exportinterfaceParamsMap{[RoutePath.Index]:IndexParam;[RoutePath.About]:AboutPara米;[RoutePath.User]:UserParam;}exportclassRouterHelper{publicstaticreplace(routePath:T,params:ParamsMap[T]){Router.replace({path:routePath,query:params})}publicstaticpush(routePath:T,params:ParamsMap[T]){Router.push({path:routePath,query:params})}}