TypeScript - 问题及实战

问题及实战

  1. 你觉得使用TS的好处是什么?
    1.1 Ts是JS的加强版,给JS添加了可选的静态类型和基于类的面向对象编程,拓展了JS语法,TS的功能比JS只多不少
    1.2 TS面向对象的编程语言,包含类和接口的概念
    1.3 TS在开发阶段就能给出编译错误,而JS则要在运行时才能暴露
    1.4 是一种强类型语言,你可以明确的知道各种数据类型,代码可读性极强,几乎每个人很快理解
    1.5 TS中有很多很方便的特性,比如可选链 // option chain
  const obj = response;
  if(obj && obj.aa && obj.aa.bb){
    // ...
  }

  if(obj?.aa?.bb){
    // ...
  }
  1. type 和 interface 的异同?

用interface来描述数据结构,用type来描述类型

2.1 都支持描述一个对象或者函数

  interface User{
    name: string;
    age: number;
  }
  type User = {
    name = string;
    age = number;
  }

2.2 都允许扩展 extends

  type Name = {
    name: string;
  }

  interface User extends Name {

  }

2.3 只有type可以做的事情
type可以申请基本类型别名,联合类型,元祖等类型

  type Name = string;

  interface Dog {
    wong();
  }
  interface Cat {
    miao();
  }
  type Pet = Dog | Cat;

  type PetList = [Dog, Cat]
  1. 如何基于一个已有类型,扩展出一个大部分内容相似,但是部分区别的类型?

Pick Omit

  interface Test {
    name: string;
    sex: number;
    height: string;
  }

  type Sex = Pick<Test, 'sex'> // 保证了Sex始终是number
  const a: Sex = {sex: 1};

  type WithoutSex = Omit<Test, 'sex'>;
  const b: WithoutSex = {name: 'cxx', height: 'xxxx'};

通过泛型!!!

  1. 什么是泛型?泛型的具体使用?

泛型是指在定义函数、接口或者类的时候,不预先指定具体的类型,使用时再去指定类型的一种特性。

  interface Test<T = any>{
    userId: T
  }

  type TestA = Test<string>; 
  // { userId: string }
  type TestB = Test<number>; 
  // { userId: number }
  1. 用装饰器实现一个计算函数运行时间的逻辑
  export function measure(target: any, name: any, descriptor: any){
    const oldValue = descriptor.value;

    descriptor.value = async function () {
      const start = Date.now();
      const res = await oldValue.apply(this, arguments);

      console.log(`${name}执行耗时 ${Date.now() - start}`);
      return res;
    }

    return descriptor;
  }
  1. 缓存的装饰器
  const cacheMap = new Map();

  export function measure(target: any, name: any, descriptor: any){
    const oldValue = descriptor.value;

    descriptor.value = async function (...args: any) {
      // 函数名 + 参数来保证缓存key的唯一性
      const cacheKey = name + JSON.stringfiy(args);
      if(!cacheMap.get(cacheKey)){
        // Promise.resolve将val执行结果强行包装为promise
        // 报错 catch的时候, 清空缓存. 下次重新执行
        const cacheValue = Promise.resolve(val.apply(this, arg).catch(() => cacheMap.set(cacheKey, null)));
        cacheMap.set(cacheKey, cacheValue)
      }
      return cacheMap.get(cacheKey)
    }

    return descriptor;
  }
  1. 实现一个路由跳转,通过TS约束参数的routerHelper

      // router / index.ts
      export enum RouterPath {
     Index = '/',
     About = '/about',
     User = '/user',
      }
    
      // routerHelper
      import { Dictionary } from 'vue-router/types/router';
      import Router, { RoutePath } from '../router';
    
      export type BaseRouteType = Dictionary<string>;
    
      export interface IndexParam extends BaseRouteType {
     name: string;
      }
      export interface AboutParam extends BaseRouteType {
     testName: string;
      }
      export interface UserParam extends BaseRouteType {
     userId: string;
      }
    
      export interface  ParamsMap {
     [RoutePath.Index]: IndexParam;
     [RoutePath.About]: AboutParam;
     [RoutePath.User]: UserParam;
      }
    
      export class RouterHelper {
     public static replace<T extends RouterPath>(routePath: T, params: ParamsMap[T]){
       Router.replace({
         path: routePath,
         query: params
       })
     }
     
     public static push<T extends RouterPath>(routePath: T, params: ParamsMap[T]){
       Router.push({
         path: routePath,
         query: params
       })
     }
      }
0 声望
0 粉丝
0 条评论
推荐阅读
「多图预警」完美实现一个@功能
一天产品大大向 boss 汇报完研发成果和产品业绩产出,若有所思的走出来,劲直向我走过来,嘴角微微上扬。产品大大:boss 对我们的研发成果挺满意的,balabala...(内心 OS:不听,讲重点)产品大大:咱们的客服 I...

wuwhs40阅读 4.8k评论 5

封面图
ESlint + Stylelint + VSCode自动格式化代码(2023)
安装插件 ESLint,然后 File -&gt; Preference-&gt; Settings(如果装了中文插件包应该是 文件 -&gt; 选项 -&gt; 设置),搜索 eslint,点击 Edit in setting.json

谭光志34阅读 20.7k评论 9

安全地在前后端之间传输数据 - 「3」真的安全吗?
在「2」注册和登录示例中,我们通过非对称加密算法实现了浏览器和 Web 服务器之间的安全传输。看起来一切都很美好,但是危险就在哪里,有些人发现了,有些人嗅到了,更多人却浑然不知。就像是给门上了把好锁,还...

边城32阅读 7.3k评论 5

封面图
涨姿势了,有意思的气泡 Loading 效果
今日,群友提问,如何实现这么一个 Loading 效果:这个确实有点意思,但是这是 CSS 能够完成的?没错,这个效果中的核心气泡效果,其实借助 CSS 中的滤镜,能够比较轻松的实现,就是所需的元素可能多点。参考我们...

chokcoco24阅读 2.2k评论 3

在前端使用 JS 进行分类汇总
最近遇到一些同学在问 JS 中进行数据统计的问题。虽然数据统计一般会在数据库中进行,但是后端遇到需要使用程序来进行统计的情况也非常多。.NET 就为了对内存数据和数据库数据进行统一地数据处理,发明了 LINQ (L...

边城17阅读 2k

封面图
过滤/筛选树节点
又是树,是我跟树杠上了吗?—— 不,是树的问题太多了!🔗 相关文章推荐:使用递归遍历并转换树形数据(以 TypeScript 为例)从列表生成树 (JavaScript/TypeScript) 过滤和筛选是一个意思,都是 filter。对于列表来...

边城18阅读 7.8k评论 3

封面图
Vue2 导出excel
2020-07-15更新 excel导出安装 {代码...} src文件夹下新建一个libs文件夹,新建一个excel.js {代码...} vue页面中使用 {代码...} ===========================以下为早期的文章今天在开发的过程中需要做一个Vue的...

原谅我一生不羁放歌搞文艺14阅读 20k评论 9

0 声望
0 粉丝
宣传栏