Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support generic type for jiti.import<T> #331

Merged
merged 1 commit into from
Oct 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});