首页 > 解决方案 > 在 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 文件中导入类型吗?

标签: typescript

解决方案


向文件添加导入使其成为模块。所以在一个模块中,如果你声明一个接口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如果您使用来自其他模块的大量类型,则更容易。


推荐阅读