gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:37:35 25 4
gpt4 key购买 nike

我想在由 react-scripts 生成的文件中导入类型。

我创建了 this minimal repo这说明了问题。

到目前为止我有这个:

// 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 不再位于全局命名空间中,我会收到此错误:

Cannot find name 'renderWithRouter'.

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

最佳答案

向文件添加导入使其成为一个模块。所以在一个模块中,如果你声明一个接口(interface) Window,它被声明为该模块的本地接口(interface)。

如果你想使用导入,但仍然保持全局声明,你有两个选择:

使用声明全局

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;
}

使用导入类型

interface Window {
env: any;
}

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

任何一个版本都可以,如果您使用来自其他模块的大量类型,declare global 会更容易。

关于typescript - 在 react-scripts 中导入 react-app-env.d.ts 中断 tsc 构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56752331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com