react native中typescript怎么声明全局变量,
我之前没有用TS,声明是通过global.xxx='xxx'
是可以的.
现在换成TS要怎么写呢?
我直接写global.xxx='xxx'
也是可以的,但是WS报了个错Error:(7, 8) TS2339:Property 'xxx' does not exist on type 'GlobalStatic'.
想问下正确的定义是怎么写的
react native中typescript怎么声明全局变量,
我之前没有用TS,声明是通过global.xxx='xxx'
是可以的.
现在换成TS要怎么写呢?
我直接写global.xxx='xxx'
也是可以的,但是WS报了个错Error:(7, 8) TS2339:Property 'xxx' does not exist on type 'GlobalStatic'.
想问下正确的定义是怎么写的
没用过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一样任意地写。
1 回答1.6k 阅读✓ 已解决
2 回答1.2k 阅读✓ 已解决
2 回答999 阅读✓ 已解决
1 回答973 阅读✓ 已解决
2.3k 阅读
1 回答626 阅读✓ 已解决
929 阅读
2 回答1.2k 阅读✓ 已解决
2 回答1.2k 阅读✓ 已解决
1 回答446 阅读✓ 已解决
1 回答663 阅读✓ 已解决
1.8k 阅读