Search code examples
typescriptimportnamespacesexportdeclare

How can create a nested d.ts file?


I'm building a module that can be used both in JS & TS. As far as I know, when create a module in JS, create a separate d.ts file.(Of course can make using TS and compile to JS). Anyway I chose to make d.ts file.

For example.

// common.d.ts

declare namespace common {
  export const method: string => string;
}
export = common;

Next,

// utils.d.ts
import * as u from './common';
declare namespace utils {
  export const common: u // Causing an error.
}
export = utils;

And I got this error: The namespace 'u' can not be used as a format. I want to write this to unify import addresses.

import { common as u } from '/utils';
u.method('Any params');

I guess, maybe I can get the declarations from the t.ds file and assign them. But I do not know how. Anybody help me!


Solution

  • Replacing export const common: u with export const common = u will remove the error but will copy only the value meaning of u; interfaces and type aliases defined in common.d.ts won't be accessible via this common constant. export import common = u is better: it copies all meanings. But most people would consider it even better to remove the pointless combination of a namespace and an export assignment and move the individual exports from the namespace to the top level of the module; then you can use ECMAScript export as syntax instead of a TypeScript alias.

    // common.d.ts
    export const method: string => string;
    
    // utils.d.ts
    import * as u from './common';
    export { u as common };