根目录 index.d.ts 中子文件夹的类型

Typings for sub-folders inside a root index.d.ts

我们为 material-ui@next 创建了类型,并希望将它们与我们在上一个测试版中所做的库一起发布。

这里是link到index.d.ts

但是打字以其当前形式不可用。在开发中,它们在本地使用并且运行良好,但是当使用库发送文件时,TypeScript 似乎使用了不同的发现策略。

所有引用子文件夹(例如 declare 'material-ui/Button/Button')的类型都不会被发现是 TypeScript。导入组件时会出现错误:

[ts]
Could not find a declaration file for module 'material-ui/Button/Button'. '<project path>/node_modules/material-ui/Button/Button.js' implicitly has an 'any' type.
  Try `npm install @types/material-ui/Button/Button` if it exists or add a new declaration (.d.ts) file containing `declare module 'material-ui/Button/Button';`

npm_modules 文件夹中使用时,TypeScript 是否不接受声明其他导入?因为如前所述,在本地使用它们甚至将它们移动到 @types/material-ui 将使它们工作。

此外,TypeScript 似乎找到了 index.d.ts,因为从 "root" 导入有效 (import { Button} from 'material-ui')。

所以,事实证明 TypeScript 处理 node_modules/@types/*node_modules/* 内部的类型略有不同:

@types 中的类型称为增强模块。它们是全局的,其中的所有内容都将在您的项目代码中。这就是为什么访问子模块声明(如 material-ui/Button/Button)有效。

常规 npm 模块被视为(常规)模块。因此,如果您导入一个子文件夹,该子文件夹必须包含类型。 TypeScript 不会转到模块的根目录并检查那里的类型是否有扩充模块。

这意味着您 (a) 必须将输入内容发布到 DefinitelyTyped 或为每个子文件夹和文件创建 .d.ts 文件。

您可以在此处找到更长的解释:https://github.com/Microsoft/TypeScript/issues/17945

我对此进行了一些调查;很混乱。

据我所知,在子模块中定义的 index.d.ts 将起作用 如果在项目中的任何地方有对该文件的任何引用 而它不包含 module-less 声明。

例如,这个有效:

// node_modules/b/index.d.ts
declare module 'b/sub' {
  export function boo(): void;
}

declare module 'b' {
  export function bla(): void;
}

// index.ts
import { boo } from 'b/sub';

boo();

// xedni.ts
import { bla } from 'b';

bla();

但是,删除 xedni.ts 并且 index.ts 中的导入将停止工作。

/// <reference types="b" />添加到index.ts或在tsconfig.json中设置types: ["b"]将使其再次工作。

export function bah(): void; 添加到 index.d.ts,但似乎无法使其正常工作。

我发现这种行为很不直观...