暂无图片
暂无图片
2
暂无图片
暂无图片
暂无图片

TypeScript高级技巧: 提取对象类型

背井 2021-03-03
11107

现在无论是前端,还是基于Node.js的后端,对TypeScript使用越来越多。今天我们说一个TypeScript高级使用技巧——提取已有对象的类型。




在ts中,通常我们是先声明类型,再创建该类型的对象:

    type User = {
    name: string,
    age: number
    }


    const me: User = { name: 'Youmoo', age: 18 };


    在某些情况下我们并不知道一个对象的类型,(如引用三方库的对象,而三方库并没有暴露该对象的类型时)

    我们可以借助ts,让它帮我们推断出对象类型:


        const animal = { type: 'cat', name: 'Tom' };


      // 对于以上对象,我们需要提取出它的类型,并创建一个同类型的对象
      type Animal = typeof animal;


      // 定义一个同类型的对象
      const mouse: Animal = { type: 'mouse', name: 'Jerry' };


      在visual studio code中,可以看到ts帮我们正确地推导出了Animal类型:




      以上是简单的object对象,若我们想提取数组内元素的类型呢?

      方法有多种。


      一、利用下标提取元素类型


        type Animals = Array<{ typestring, name: string }>;
        type Animal = Animals[number];


        二、利用conditional+infer


          type Animals = Array<{ typestring, name: string }>;
          type Animal = Animals extends (infer T)[] ? T : never;




          有了以上技巧,可以引出一些有意思的玩法。


          比如,将string数组中的元素提取为常量类型


            const valid_answers = ['yes', 'no', 'answer'] as const;
            type Answer = (typeof valid_answers)[number];
            const ans1: Answer = 'yes';// 没问题
            const ans2: Answer = 'nope';// 编译不通过


            其中Answer的类型定义是:



            我们甚至可以继续向内,提取更深层的字段类型


              type Foo = { x: Array<{ y: string }> };
              type TypeY = Foo['x'][number]['y'];


              你说,TypeY是什么类型呢?



              文章参考自推文: https://twitter.com/sulco/status/1215255647056486403

              文章转载自背井,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

              评论