【问题标题】:Typings for sub-folders inside a root index.d.ts根 index.d.ts 中子文件夹的类型
【发布时间】:2018-01-29 23:44:39
【问题描述】:

我们为 material-ui@next 创建了类型,并希望将它们与库一起提供,我们在上一个测试版中就这样做了。

这是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,因为从“根”导入有效 (import { Button} from 'material-ui')。

【问题讨论】:

  • Typescript 自动搜索 @types 中的类型,我相信,在 package.json 中带有 typings 键的节点包。你的包清单或其他地方有任何指向index.d.ts 的东西吗?
  • 是的,TS 也能找到类型。像{ Button } from ' material-ui' 一样导入有效。

标签: typescript material-ui definitelytyped


【解决方案1】:

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

@types 中的输入是所谓的增强模块。它们是全球性的,其中的所有内容都将在您的项目代码中。这就是访问子模块声明(如material-ui/Button/Button)有效的原因。

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

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

你可以在这里找到更详细的解释:https://github.com/Microsoft/TypeScript/issues/17945

【讨论】:

  • 真的希望有更多的记录。通常,开发人员在必须进行故障排除时会摆弄打字,这方面缺乏文档可能会导致打字稿被解雇
【解决方案2】:

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

据我所知,在子模块中定义的index.d.ts 将起作用如果项目中的任何位置对该文件有任何引用,并且它不包含无模块声明。

例如,这是有效的:

// 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 中的导入将停止工作。

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

将export function bah(): void; 添加到index.d.ts 似乎没有办法让它工作。

我觉得这种行为很不直观......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-16
    • 2018-07-30
    • 2013-01-02
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多