6

I have the React type definition file (that is declared using an external module). In my source files, I usually do:

import * as R from "react"

and can then happily use R.createElement(... etc in a strongly typed fashion.

What I want is to not have to import R in every file, and instead have it as a global declaration (yes, I'm willing to polute the global namespace with a few variables). I've tried:

import * as React from "react";
declare var R : React;

This doesn't work though, I get "Cannot find name 'React'". Is there another way to export the entire module as global?


Edit 1 - I should have made clearer: I'm interested in how to export a global type definition in a .d.ts file. So assume I've attached R to window already. Now I need typescript to know that R is of type React module.

4

4 回答 4

5

而是将其作为全局

这有两个方面:global type declaration打字稿和global variable availabilityJavaScript 消费。

全局类型声明

如果文件中没有根级别的导入导出,则A.d.ts或声明仅有助于全局名称声明空间。所以有一个文件,它将是https://github.com/borisyankov/DefinitelyTyped/blob/master/react/react.d.ts形式的编辑版本(而不是)。globalreact.d.tsdeclare module Rdeclare module "react"

全局变量导出

你需要把它放在window浏览器的情况下。因此,请在文件中执行以下操作makeReactGlobal.ts

var R = require('react'); 
(<any>window).R = R

然后在你的应用程序main中让这个文件有一个依赖项,以确保它在你的任何其他代码之前执行。

于 2015-05-14T00:13:07.443 回答
1

declare关键字未在全局范围内声明变量。此关键字用于全局范围内将存在变量并且您希望在 TypeScript 中使用它而不会出现编译错误的情况。

你可以声明一个全局变量:

import * as R from "react";
window.R = R;
于 2015-05-14T00:05:57.337 回答
1

就像@basarat 说的,这看起来不太可能。@ahejlsberg 本人在 github 上讨论了这个问题:https ://github.com/Microsoft/TypeScript/issues/3180#issuecomment-102523512 。

于 2015-05-18T11:05:26.447 回答
0

你已经很接近了(把它放在一个.d.tstsc 可以找到的文件中):

import * as React from "react";

declare global {
  const R: typeof React;
}

(请注意添加的“typeof”。尚未使用 React 进行测试,但它适用于 Vue。)

于 2021-11-19T13:56:40.213 回答