关于javascript:Node.js全局变量和TypeScript

Node.js global variable and TypeScript

我需要一些强类型的全局变量。

如此处所述:扩展node.js中的TypeScript全局对象,以便将字段添加到global变量中,我需要添加一个.d.ts文件,该文件扩展了node.d.ts中指定的global接口。

另外,正如Basarat所述:

Your file needs to be clean of any root level import or exports. That
would turn the file into a module and disconnect it from the global
type declaration namespace.

现在,我需要在global接口上具有字段,其类型是我创建的自定义接口:

1
2
3
4
5
6
declare namespace NodeJS{
    interface Global {
        foo: Foo
        bar: Bar
    }
}

我非常不愿意使用any类型。

我可以将所有接口声明移动/复制到此声明文件中,但这对我来说是一个糟糕的解决方案,因为Foo和Bar反过来会聚集其他接口的许多字段,包括Moment等第三方接口。

我需要针对这个悖论的解决方案


我发现这个作品。

有一个文件可以使用任何类型在NodeJS.Global接口上声明该属性。 此文件必须清除导入或引用。

节点

1
2
3
4
5
declare namespace NodeJS{
    interface Global {
        foo: any
    }
}

然后,在第二个文件中,声明一个具有正确类型的全局变量。

全球数据

1
2
3
4
5
6
7
import IFoo from '../foo'

declare global {

  const foo:Ifoo

}


简单又容易

Global类中创建静态属性

1
2
3
export class Global {
    static name: string
}

然后毫不犹豫地使用它

1
2
3
4
5
6
7
8
export class MyClass {

   constructor() {
      Global.name = 'Wasif'
      console.log(Global.name)
   }

}