0

I am able to make the linter recognize global.expect as a variable with the following

// types.d.ts
namespace NodeJS {
  interface Global {
    expect: any
  }
}

However, it won't autocomplete any of expect() methods. I figure it's cause it's any.

I'm trying to type it to the expect imported type but it's not working, Here's what I've tried.

import expectExport from 'expect';

namespace NodeJS {
  interface Global {
    expect: expectExport
  }
}

What am I missing?

Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206

2 Answers2

1

TL;DR

Do the following in global-expect.ts:

import expectExports from "expect";

declare global {
    namespace NodeJS {
        interface Global {
            expect: typeof expectExports;
        }
    }
}

global.expect = expectExports;

Make sure you import/execute the file somewhere at your application's entry point, e.g. index.ts:

import "./global-expect";

Then you can use this anywhere:

global.expect(...); // (property) NodeJS.Global.expect: <...>(actual: ...) => Matchers<...>

Explanation

  1. the NodeJS namespace is in the global scope so it must be declared that way inside of a module:
    declare global {
      namespace NodeJS {
        ...
      }
    }
    
  2. the type expect property in the Global interface must be a type of the "expect" exports - not the instance of it. So it must be declared like this:
    expect: typeof expectExports;
    
  3. then you actually have to set the property:

    import expectExports from "expect";
    
    ...
    
    global.expect = expectExports;
    
DoronG
  • 2,576
  • 16
  • 22
0

A bit simpler way to accomplish it is to augment NodeJS namespace in some d.ts file

declare namespace NodeJS {
    interface Global {
        expect: typeof import("expect")
    }
}

It also may be handy to use expect as a global variable, so you can make a global.d.ts file near to tsconfig.json and put declaration there

// global.d.ts
declare const expect: typeof import("expect");
Shlang
  • 2,495
  • 16
  • 24