继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【十月打卡】第60天 TypeScript(16)

康遇
关注TA
已关注
手记 76
粉丝 3
获赞 9

类型描述文件

  • 类型描述文件格式为*.d.ts
  • 全局或者模块需要declare来声明

全局

如下以jquery来举例

// index.html
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
<script src="./src/index.ts"></script>

// index.ts
$(function () {
  $('body').html('<div>Hello world</div>');
});

针对上面用法的类型描述文件:jquery.d.ts

interface JqueryInstance {
  html: (html: string) => JqueryInstance;
}

// 方式一:函数重载
declare function $(readyFn: () => void): void;
declare function $(selector: string): JqueryInstance;

// 方式二:使用interface,实现函数的重载
interface Jquery {
  (readyFn: () => void): void;
  (selector: string): JqueryInstance;
}
declare var $: Jquery;

如果jquery增加了对象以及类怎么处理?

$(function () {
  $('body').html('<div>Hello world</div>');
  new $.fn.init();
});
interface JqueryInstance {
  html: (html: string) => JqueryInstance;
}

declare function $(readyFn: () => void): void;
declare function $(selector: string): JqueryInstance;

// 命名空间实现对象以及类进行类型定义
declare namespace $ {
  namespace fn {
    class init {}
  }
}

模块

如果jquery是以模块来引入,类型描述文件该怎么处理呢

import $ from 'jquery';
$(function () {
  $('body').html('<div>Hello world</div>');
  new $.fn.init();
});
  • 声明模块加上module
  • 通过export导出
declare module 'jquery' {
  interface JqueryInstance {
    html: (html: string) => JqueryInstance;
  }

  // 重载
  function $(readyFn: () => void): void;
  function $(selector: string): JqueryInstance;
  namespace $ {
    namespace fn {
      class init {}
    }
  }

  // 导出
  export  = $;
}

泛型结合keyof

先看下面实例
TS报错:return this.info[key]
原因:因为getInfo传入的参数无法保证是name、age或者gender中的一个

interface Person {
  name: string;
  age: number;
  gender: string;
}

class Teacher {
  constructor(private info: Person) {}
  getInfo(key: string) {
    return this.info[key];  // 报错
  }
}

const teacher = new Teacher({
  name: 'tz',
  age: 30,
  gender: 'male',
});

teacher.getInfo('name');

通过keyof可以来解决, keyof遍历Person的属性

interface Person {
  name: string;
  age: number;
  gender: string;
}

class Teacher {
  constructor(private info: Person) {}
  getInfo<T extends keyof Person>(key: T): Person[T] {
    return this.info[key];
  }
}

const teacher = new Teacher({
  name: 'tz',
  age: 30,
  gender: 'male',
});

teacher.getInfo('name');
打开App,阅读手记
2人推荐
发表评论
随时随地看视频慕课网APP