typescript 全局定义module

为了module的interface可以全局环境下动态添加定义

// ./src/global.d.ts
declare module FileServeModule {
    export interface IConfig {
        maxClients: number;
    }
}
// ./src/file-hand.ts
declare module FileServeModule {
    export interface IConfig {
        port: number;
    }
}
// ./src/main.ts
let config: FileServeModule.IConfig = {
    maxClients: 123,
    port: 123
}

编译器并没有检查出任何错误,但是运行时报找不到FileServeModule,很想实现全局定义,方便扩展
launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
      {
        "type": "node",
        "request": "launch",
        "name": "Launch Program",
        // "program": "${workspaceFolder}\\index.js",
        "args": [
          //"${file}" // 入口文件
          "${workspaceFolder}/src/main.ts"
        ],
        "runtimeArgs": [
          "--nolazy",
          "-r",
          "ts-node/register"
        ],
        "sourceMaps": true,
        "cwd": "${workspaceRoot}",
        "protocol": "inspector",
        "console": "integratedTerminal",
        "internalConsoleOptions": "neverOpen"
      }
    ]
  }
阅读 6.3k
3 个回答

我现在的解决办法是按照文档来(之前文档看的不够仔细)
./types/FileServeModule/global.d.ts

declare module FileServeModule {
    export interface IConfig {
        maxClients: number;
    }
}
import { Client } from './client/client';
import * as GFileServe from 'GFileServe';
export async function Bootstrap() {
    // console.log('start');
    let serve = new Serve({servePort: 8002});
    let client = new Client({host: '127.0.0.1', port: 8002});
    let config: GFileServe.IConfig = {
        servePort: 123,
        env: '123'
    }
    await serve.start();
    client.start();
}
Bootstrap();
declare module 'GFileServe'{
    export interface IConfig {
        env: string;
    }
}

上面这样写完全没的问题,玩美……

package.json -> 添加 "typings": "./src/global.d.ts",

then tsconfig.json里加入

"typeRoots": [
      ".src/global.d.ts",
      "./node_modules/@types"
    ],
    "include": [
      ".src/.ts",
      "src/**/*",
      ".src/global.d.ts"
    ],

重启项目 试试吧

根据文档和我的理解,有些外部模块没有 ts 声明文件,module是用来声明这些外部模块。
一般这么用:

/// <reference path="node.d.ts"/>
import * as URL from "url";
let myUrl = URL.parse("http://www.typescriptlang.org");

文档

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进