timocov / dts-bundle-generator

A tool to generate a single bundle of dts with types tree-shaking
MIT License
762 stars 40 forks source link

[bug] Changes type to reference to the wrong variable #323

Open nicolo-ribaudo opened 6 months ago

nicolo-ribaudo commented 6 months ago

Bug report

Input code

// index.ts
import { fn } from "./other-file";
export function a() {}
a.fn = fn;
// other-file.ts
export function fn() {}

Actual output

// Generated by dts-bundle-generator v9.5.1

declare function fn(): void;
export declare function a(): void;
export declare namespace a {
    var fn: typeof fn;
}

export {};

Notice that the type of var fn refers to var fn and not to function fn

Expected output

Maybe this?

// Generated by dts-bundle-generator v9.5.1

declare function fn(): void;
type fn_type = typeof fn;
export declare function a(): void;
export declare namespace a {
    var fn: fn_type;
}

export {};

or this

// Generated by dts-bundle-generator v9.5.1

declare function fn$1(): void;
export declare function a(): void;
export declare namespace a {
    var fn: typeof fn$1;
}

export {};

Additional context

This also happens in rollup-plugin-dts

timocov commented 4 months ago

https://www.typescriptlang.org/dev/bug-workbench/?#code/PTAEAEGcAsHsHcCiBbAlgFwFAgjBKN0BTAEwDFUAbIgLlFQDsSiAPAOhLfUmzHGYDGlAIYAnYelSwGddKICuRTLwgAzKkQbDktek1ZceqZAAdYo9KADeoVQ1ABfW6NjJQAIjbBY6aEVEAtOrU7gDcmKxmFrbyDAKS0qDCABQAlNYOmMJsdqAAvLYM4bx8wZrauj5+gWWGESxRlqqx8VL2dml0AG6wqCQZQA

timocov commented 4 months ago

So the issue is that the compiler generates dts like so:

export declare function a(): void;
export declare namespace a {
    var fn: typeof import("./other-file").fn;
}

And then the tool traverse this and removes all dynamic imports of local files (it happens here) and resolves the name on the right with its registered "local" name. The issue is that the tool doesn't consider any names declared in namespaces thus fn stays fn, not being renamed to something fn$1 or so.