Skip to content

Commit

Permalink
feat: support generic type for jiti.import<T> (#331)
Browse files Browse the repository at this point in the history
  • Loading branch information
hywax authored Oct 13, 2024
1 parent 5442474 commit b789385
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 5 deletions.
4 changes: 2 additions & 2 deletions lib/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ export interface Jiti extends NodeRequire {
*
* If you need the default export of module, you can use `jiti.import(id, { default: true })` as shortcut to `mod?.default ?? mod`.
*/
import(
import<T = unknown>(
id: string,
opts?: JitiResolveOptions & { default?: true },
): Promise<unknown>;
): Promise<T>;

/**
* Resolve with ESM import conditions.
Expand Down
5 changes: 4 additions & 1 deletion src/jiti.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,10 @@ export default function createJiti(
evalModule(source: string, options?: EvalModuleOptions) {
return evalModule(ctx, source, options);
},
async import(id: string, opts?: JitiResolveOptions & { default?: true }) {
async import<T = unknown>(
id: string,
opts?: JitiResolveOptions & { default?: true },
): Promise<T> {
const mod = await jitiRequire(ctx, id, { ...opts, async: true });
return opts?.default ? (mod?.default ?? mod) : mod;
},
Expand Down
4 changes: 2 additions & 2 deletions test/bun.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ test("hmr", async () => {
let value;

await writeFile(tmpFile, "export default 1");
value = (await _jiti.import(tmpFile, { default: true })) as any;
value = await _jiti.import<number>(tmpFile, { default: true });
expect(value).toBe(1);

await writeFile(tmpFile, "export default 2");
value = (await _jiti.import(tmpFile, { default: true })) as any;
value = await _jiti.import<number>(tmpFile, { default: true });
expect(value).toBe(2);
});

0 comments on commit b789385

Please # to comment.