Search code examples
typescriptvitest

Type augmentation in library


I want to write a library with a vitest custom matcher function in TypeScript.

Following the documentation, I've added a vitest.d.ts file with the necessary augmentations. This works fine, but my problem is, that any other project importing my library doesn't know about the augmentation, so calling the new matcher results in a TypeScript error:

expect(data).toMatchTheTypicalExpectations()
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

error TS2339: Property 'toMatchTheTypicalExpectations' does not exist on type 'Assertion<Data>'.

Sure, everybody could add the augmentation themselves, but somehow exporting the augmentation as well would be far better.


Solution

  • After trying a lot of things, I found a solution for my problem.

    First, I've added a vitest.ts (not d.ts!) file to my source folder of my library, containing the augmentations:

    export * from "vitest"
    
    declare module 'vitest' {
      interface Assertion<T> {
        toMatchTheTypicalExpectations(): T
      }
      interface AsymmetricMatchersContaining {
        toMatchTheTypicalExpectations(): unknown
      }
    }
    

    Now, I've added the following line to my main index.ts file

    import "./vitest.js"
    

    Building the library's types includes the vitest.d.ts together with its inclusion in index.d.ts, so that it is actually known by any user of the library.