导入react-scripts react-app-env.d.ts中断了tsc构建

dag*_*da1 7 typescript

我想在由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;
Run Code Online (Sandbox Code Playgroud)

如果取消注释任何导入语句并运行tsc,则renderWithRouter不再在全局名称空间中,并且出现此错误:

找不到名称“ renderWithRouter”。

我不能在.d.ts文件中导入类型吗?

Tit*_*mir 7

将导入添加到文件使其成为模块。因此,在模块中,如果您声明一个接口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;
}
Run Code Online (Sandbox Code Playgroud)

使用import类型

interface Window {
  env: any;
}

declare function renderWithRouter(ui: any, { route, history, }?: {
  route?: string;
  history?: import('history').History;
}): import('react-testing-library').RenderResult;
Run Code Online (Sandbox Code Playgroud)

两种版本都可以使用,declare global如果您使用其他模块中的许多类型,则更容易。