typescript - 在 react-scripts 中导入 react-app-env.d.ts 会破坏 tsc 构建
问题描述
我想在由 react-scripts 生成的文件中导入类型。
我创建了这个显示问题的最小存储库。
到目前为止我有这个:
// import * as React from 'react';
// import { MemoryHistory } from 'history';
// import { RenderResult } from 'react-testing-library';
interface Window {
env: any;
}
type ContextDefaultValue = [string, (val: string) => void];
/* global function for rendering with Router */
declare function renderWithRouter(ui: any, { route, history, }?: {
route?: string;
history?: any;
}): any;
如果我取消注释任何导入语句并运行 tsc,则 renderWithRouter 不再位于全局命名空间中,并且出现此错误:
找不到名称“renderWithRouter”。
我不能在 .d.ts 文件中导入类型吗?
解决方案
向文件添加导入使其成为模块。所以在一个模块中,如果你声明一个接口Window
,它就被声明为该模块的本地。
如果您想使用导入,但仍保持全局声明,您有两种选择:
采用declare global
import * as React from 'react';
import { History } from 'history';
import { RenderResult } from 'react-testing-library';
declare global {
interface Window {
env: any;
}
declare function renderWithRouter(ui: any, { route, history, }?: {
route?: string;
history?: History;
}): RenderResult;
}
使用import
类型
interface Window {
env: any;
}
declare function renderWithRouter(ui: any, { route, history, }?: {
route?: string;
history?: import('history').History;
}): import('react-testing-library').RenderResult;
任何一个版本都可以使用,declare global
如果您使用来自其他模块的大量类型,则更容易。
推荐阅读
- python - Python - 从列表创建数组?!
- javascript - Vue:监视路径名以检测 URL 更改
- asp.net - 混合应用程序的安全性改进
- angular - Angular 6 选择输入测试
- ruby - 如何在 ruby 中从希伯来语 utf-8 中去除元音/nekudot/变音符号?
- r - 如何绘制从R中的循环中提取的单独线
- c# - 在外部 sd 卡上创建目录。(写访问错误)
- linux - 如何在当前文件夹和所有子文件夹中的所有文件中搜索特定文件内容
- c# - WebRequest 指定 SSL/TLS 密码
- ios - UICollectionView 在单元格中显示错误的图像