#Wildcard Module Augmentation in `.ts`

9 messages · Page 1 of 1 (latest)

carmine cipher
#

The following code in a .ts file:

declare module '*.txt' {
    const module: string
    export default module
}

Does not work, giving error:

Invalid module name in augmentation, module '*.txt' cannot be found. ts(2664)

However, putting it in a .d.ts file does work as expected.
Is this intended, can I achieve the same in a .ts file rather than .d.ts?

steel jewel
#

it's not specifically about .ts vs .d.ts, it's about whether the file is a real module or not. you can't use that syntax in modules, but it should work in a .ts file that's not parsed as a module

this is what the handbook says about it:

TypeScript supports a syntax in script (non-module) files for declaring a module that exists in the runtime but has no corresponding file. These ambient modules usually represent runtime-provided modules, like "fs" or "path" in Node.js: […]

carmine cipher
#

Ah I see, what I'm trying to do is ambient module declaration which only works in a non module file, and module augmentation which works in a module file also shares the same syntax, so the code gets treated as module augmentation and hence the error.

#

For projects with a bundler, I put the code in a file without any top level import/export so it gets treated as a non module, and it works as intended.

#

I guess this wouldn't work if you are in environments where TS treats everything as a module, like module: Node16 with ESM. But I guess it's also not that big of an issue since you wouldn't need wildcard in that case.

steel jewel
#

yeah, that sounds right. just curious though: why aren't you using a .d.ts file? i think that would work even in module: Node16-like scenarios

carmine cipher
#

With skipLibCheck turned on, .d.ts files don't get type checked.

steel jewel
#

woah, even ones not in node_modules? TIL; never noticed that (but i don't write many .d.ts files)

carmine cipher
#

I guess not really possible to avoid .d.ts in projects where everything is treated as a module then, but I'll take the work around for the other kinds of projects.