Using globalThis in Typescript

Update 2021 October

Applies to TypeScript 4.3+

Error

Element implicitly has an any type because type typeof globalThis has no index signature. ts(7017)

Solution

declare global {
  function myFunction(): boolean;
  var myVariable: number;
}

globalThis.myFunction = () => true;
globalThis.myVariable = 42;
  • IMPORTANT: This solution only works by declaring variables with var (do not use let or const).

Background

See the discussion on TypeScript issue 30139.

Traditionally, the way to specify a TypeScript declare-block in a Node.js context was as follows:

// Does not work as of October 2021 (TypeScript 4.3+)
declare global {
  module NodeJS {
    interface Global {
      myFunction(): boolean;
      myVariable: number;
    }
  }
}

tsconfig.json: noImplicitAny

Note that this error will be suppressed if the TypeScript setting noImplicitAny is set to false. It is recommended to enable noImplicitAny for better type checking.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)