I am writing a bundler plugin (e.g. vite) that can load *.sql
files directly in JS/TS. They will be transformed to valid JS modules during bundling.
Now I want to add type declarations for those files.
What I already tried
1. Wildcard declaration
Similar to most of other vite loaders, I can give *.sql
files a general type:
declare module '*.sql' {
const query: () => Promise<any>
export default query
}
But this isn’t what I need because different .sql
file has different query result, therefore they should have different types.
import queryA from './a.sql'
import queryB from './b.sql'
const resultA = await queryA()
const resultB = await queryB() // They should have different types
2. declare module
with paths
I have also tried using declare module
with a relative/absolute path of the file. This won’t work for two reasons:
-
TS errors with “Ambient module declaration cannot specify relative module name”.
-
Relative paths won’t work anyways, because one
.sql
can be imported by different TS files with different relative paths.
3. Adding a something.sql.d.ts
file next to the .sql
file
This works in theory. But in my case types will be automatically generated by a code generator instead of written manually. Lots of, everywhere-scattered generated codes are very hard to manage.
So what I’m desiring is a centralized type declaration (at least in one folder) instead of this.
Jindong Zhang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.