我想在由反应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
更容易。
如果您查看打字稿的正式文档,则非常清楚地解释了工作逻辑(包括此错误(及其结构。1,2
从模块导入
您可能会开始遇到Cannot find name 'require'.
和Cannot find name 'define'
等许多错误。在这些情况下,您可能正在使用模块。虽然您只能说服打字条来通过写出这些存在
//for node/commonjs
declare function require(path: string): any;
或
//对于requirejs/amd
declare function define(...args: any[]): any;
最好摆脱这些电话并将输入字样语法用于导入。
首先,您需要通过设置TypeScript的模块标志来启用一些模块系统。有效选项是commonjs
,amd
,system
和umd
。
如果您有以下节点/commonjs代码:
var foo = require("foo");
foo.doStuff();
或以下requirejs/amd代码:
define(["foo"], function(foo) {
foo.doStuff();
})
然后您将编写以下打字稿代码:
import foo = require("foo");
foo.doStuff();