声明文件

声明文件以.d.ts结尾,用来描述代码结构。

// jsonp 声明文件示例
type CancelFn = () => void;
type RequestCallback = (error: Error | null, data: any) => void;

interface Options {
    param?: string;
    prefix?: string;
    name?: string;
    timeout?: number;
}

declare function jsonp(url: string, options?: Options, cb?: RequestCallback): CancelFn;
declare function jsonp(url: string, callback?: RequestCallback): CancelFn;

export = jsonp;

typescript 如何加载声明文件

  • npm 包自带声明文件
    • 根目录下的index.d.ts文件
    • package.json 中的typingstypes字段
  • 外置声明文件:@types命名空间包,安装后 IDE 会作为声明文件自动加载
  • 自己写声明文件:

扩展原生对象

// index.d.ts
interface Window {
  customProp: number
}

// index.ts
window.customProp = 2  // ok

在模块内部扩展原生对象

import A from 'moduleA'

window.customProp = 2

declare global {
  interface Window {
    customProp: number
  }
}

results matching ""

    No results matching ""