Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type 'typeof globalThis' has no index signature

i get this error whenever i try to add a function to the global nodejs global namsepace in a TypeScript environment.

Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature

declaring the global namespace

declare global {
  namespace NodeJS {
    interface Global {
      signin(): string[]
    }
  }
}

so if i try this

global.signin = () => {}

it returns a

Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature

like image 592
Mhd Avatar asked Jul 22 '21 08:07

Mhd


People also ask

Has an any type Because type Typeof globalThis has no index signature?

The error "Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature" occurs when we try to access a property that doesn't exist on the global object. To solve the error, extend the global object and add types for the necessary properties.

Does not exist on type Typeof globalThis?

The "Property does not exist on type 'Window & typeof globalThis'" error occurs when we access a property that does not exist on the Window interface. To solve the error, extend the Window interface in a . d. ts file and add the property you intend to access on the window object.

What is globalThis?

The globalThis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. Unlike similar properties such as window and self , it's guaranteed to work in window and non-window contexts.


2 Answers

I was having a similar issue and I found that node's global typings were changed recently-ish; you can now override them by doing:

// global.d.ts
declare global {
    function someFunction(): string;
    var someVariable: string;
}

Note: this will not work with let or const you must use var.

// index.ts
global.someFunction = () => "some value";
global.someVariable = "some value";
like image 154
IRONM00N Avatar answered Sep 19 '22 12:09

IRONM00N


You have to use the var keyword in declare global, and remove namespace NodeJS {.
Like this:

//globals.d.ts
import type { EventEmitter } from "events";
declare global {
    var myGlobal: EventEmitter;
}
/// <reference path="globals.d.ts" />
//index.ts
// reference needs to be at top of file
import { EventEmitter } from "events";
global.myGlobal = new EventEmitter();
global.myGlobal // EventEmitter type: EventEmitter
window.myGlobal // EventEmitter type: EventEmitter

Or if you don't have any imports in the .d.ts file:

//namedoesntmatter.d.ts
declare var a: string;
//index.ts
global.a = "Hello"
global.a //Hello type: string
window.a //Hello type: string
like image 26
jackssrt Avatar answered Sep 17 '22 12:09

jackssrt