Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vitest importActual: Jest gets types, but Vitest gives "... is of type unknown"

I'm migrating from jest to vitest. In the process, I am converting these:

// Jest
const myLib = jest.requireActual("mylib.js")

to these:

// Vitest
const myLib = await vi.importActual("myLib.js")

Great, except with Jest, I get no type errors, but with Vitest, I get:

TS18046: myLib is of type unknown

I can access members of myLib, and I can see that they are typed correctly, but any access on myLib causes the error:

// Thing[] is inferred. Error is on **myLib**.things
const things: Thing[] = myLib.things

When investigating (by simply hovering over myLib in WebStorm) the type in each scenario, I see that Jest gives any for myLib's type, while Vitest gives unknown.

I have noImplicitAny: true in my tsconfig.json, so I would think I should get an error on any as well.

But anyway, why is there a difference, how can TypeScript figure out that myLib.things is of type Thing[] if myLib itself is unknown, and how am I supposed to do it?

like image 505
404usernamenotfound Avatar asked Nov 01 '25 21:11

404usernamenotfound


1 Answers

I just ran into this myself and code quality checks were yelling at me. I needed forwardRef in a mock but, as you ran into, await vi.importActual('react') was unknown;

solution

import React from 'react';
vi.mock('my-module', async () => {
    const { forwardRef } = await vi.importActual<typeof React>('react');
    ...
});

So, if you have a type definition for that module, you can just use that, but it wont infer.

like image 128
Bastiat Avatar answered Nov 04 '25 13:11

Bastiat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!