Z
ZHANK
模块与配置

声明文件 (.d.ts)

理解 declare、全局类型、模块声明、三斜线指令

声明文件 (.d.ts)

声明文件为 JavaScript 库提供类型信息,让你在 TS 中安全使用 JS 库。

学完本章你将: 理解 declare、全局类型、模块声明。


declare 关键字

typescript
// 声明全局变量
declare const APP_VERSION: string;
console.log(APP_VERSION);

// 声明全局函数
declare function initApp(config: AppConfig): void;

// 声明模块
declare module "*.svg" {
    const content: string;
    export default content;
}

declare module "*.css" {
    const styles: Record<string, string>;
    export default styles;
}

为第三方库写声明

typescript
// types/my-lib.d.ts
declare module "my-lib" {
    export function doSomething(value: string): number;
    export const version: string;
}

// 使用
import { doSomething, version } from "my-lib";
console.log(doSomething("test")); // 有类型提示

全局扩展

typescript
// 扩展全局类型
declare global {
    interface Window {
        __CUSTOM_CONFIG__: {
            apiUrl: string;
            debug: boolean;
        };
    }

    interface String {
        capitalize(): string;
    }
}

// 使用
console.log(window.__CUSTOM_CONFIG__.apiUrl);
"hello".capitalize(); // 需要实现

DefinitelyTyped

大多数流行库已有社区维护的类型声明:

bash
npm install --save-dev @types/lodash
npm install --save-dev @types/react
npm install --save-dev @types/express
typescript
// 直接使用,类型自动可用
import express from "express";
import _ from "lodash";

const app = express();
_.groupBy([1, 2, 3], String);