react native中typescript怎么声明全局变量

react native中typescript怎么声明全局变量,
我之前没有用TS,声明是通过global.xxx='xxx'是可以的.
现在换成TS要怎么写呢?
我直接写global.xxx='xxx'也是可以的,但是WS报了个错
Error:(7, 8) TS2339:Property 'xxx' does not exist on type 'GlobalStatic'.
想问下正确的定义是怎么写的

阅读 8.8k
3 个回答
declare global {
    namespace NodeJS {
        interface Global {
            xxx: string
        }
    }
}

没用过react-native
但跟浏览器里在window对象上定义全局变量应该是一样的

declare interface MyWindow extends Window {
  xxx: string;
}
declare const window: MyWindow;

大概改成

declare interface MyGlobalStatic extends GlobalStatic {
  xxx: string;
}
declare const global: MyGlobalStatic;

就可以了

如果你是想在某个文件定义一个global变量,然后在任意的文件中不通过import就可以直接引用,那么Typescript的模块是没有你想要的 global 概念的。

你必须自己包装一个static的局部变量,然后在需要的地方import引入。

// global
export var VAR_GLOBAL = 1
export const CONST_GLOBAL = 1

用的时候

import {VAR_GLOBAL} from './globals'

至于编译后运行于浏览器中的Typescript中的 window 这个特殊的对象,是可以添加任意属性的。一方面是由于浏览器支持window(运行时支持),Typescript自身也添加了相关的typing reference(编译时支持),所以才知可以当作global一样任意地写。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题