如何为module.exports导出的函数及相关接口编写对应的.d.ts类型定义文件
Let's fix your .d.ts file so it properly matches your CommonJS export pattern (module.exports = function foo()) while supporting both clean ES module imports and exporting your required types. Here's the right approach:
Working Type Definition
declare module 'mymodule' { // Export your custom types first export type Language = 'it' | 'es' | 'de'; export type Platform = 'linux' | 'winzoz'; // Declare the function signature function foo(language: Language, platform: Platform, milliseconds?: number): void; // Support both CommonJS require() and ES module import (with esModuleInterop) export default foo; export = foo; }
Why This Works
Let's break down why this solves your issues:
export = foodirectly maps to your CommonJSmodule.exports = foopattern, soconst foo = require('mymodule')works without any extra config.export default fooadds support for ES module-styleimport foo from 'mymodule'when you enableesModuleInteropin yourtsconfig.json(more on that below).- Your
LanguageandPlatformtypes are exported at the module level, so you can import them separately just like any other TypeScript type.
Import Examples
CommonJS (no config needed)
const foo = require('mymodule'); foo('it', 'linux', 1000); // Importing types (TypeScript only) const foo = require('mymodule'); import type { Language, Platform } from 'mymodule'; const lang: Language = 'es';
ES Module (with esModuleInterop enabled)
import foo from 'mymodule'; import type { Language, Platform } from 'mymodule'; const lang: Language = 'de'; foo(lang, 'winzoz');
Fixing Your Previous Attempts
Let's go over why your earlier tries didn't work:
First attempt (
export function foo):
This declares a module that exports a namedfoofunction, but your actual JS module exports the function as the entire module itself. So you'd have to import it asimport { foo } from 'mymodule', which doesn't match your CommonJS export.Second attempt (
export default foo):
WithoutesModuleInterop, TypeScript treats ES moduleimportstatements strictly and expects your CommonJS module to have adefaultproperty (which it doesn't—your module is the function itself).Third attempt (
export = foo):
This works for CommonJS, but requires the clunkyimport foo = require('mymodule')syntax for ES modules. Addingexport default fooalongside it fixes this, and your types still remain exportable.
Recommended TSConfig Settings
To make ES module imports work smoothly with CommonJS modules, add these to your tsconfig.json:
{ "compilerOptions": { "esModuleInterop": true, "allowSyntheticDefaultImports": true } }
esModuleInteroptells TypeScript to handle CommonJS modules as if they have a default export when using ESimport.allowSyntheticDefaultImportslets you writeimport foo from 'mymodule'without TypeScript throwing an error about missing a default export.
内容的提问来源于stack exchange,提问作者EuberDeveloper

