项目中使用.d.ts 为后缀的文件

1,162 阅读1分钟

声明文件(xxx.d.ts):当使用第三方库时,我们需要引用它的声明文件,才能获得对应的代码补全、接口提示等功能

    1. 下面根据官文列举声明文件的常用语法:
declare var 声明全局变量
declare function 声明全局方法
declare class 声明全局类
declare enum 声明全局枚举类型
declare namespace 声明(含有子属性的)全局对象
interface 和 type 声明全局类型
export 导出变量
export namespace 导出(含有子属性的)对象
export default ES6 默认导出
export = commonjs 导出模块
export as namespace UMD 库声明全局变量
declare global 扩展全局变量
declare module 扩展模块
    1. 工程化项目中可以创建global.d.ts文件放在src目录下
  • 重点:此文件无需引入页面,即可使用其中的声明
/**
 * global.d.ts
 * 全局声明文件
 */



 /**
  * 全局变量
  */
declare const foo: number

 /**
  * 全局函数
  */
declare function greet (name: string) :void

 /**
  * 全局对象
  */
declare namespace lib {
  function say (name: string): string {
    return '名字--' + name
  }
  let age: number
}

 /**
  * 函数重载
  */
declare function getWidget (n: number): Widget
declare function getWidget (s: string): Widget[]

 /**
  * 全局接口
  */
declare interface itername {
  readonly name: string;
  age: string | number;
  text?: string;
}

 /**
  * 全局类型别名
  */
declare type greetlike = string | (() => string) | greet

 /**
  * 全局类型模块(命名空间)
  */
declare namespace GNI {
  interface A {}
  interface B {}
}

 /**
  * 全局类
  */
 declare class Greeter {
   constructor(greeting: string)
   greeting: string
   print (): void
 }