【问题标题】:Reference definition from ts-check JS file来自 ts-check JS 文件的引用定义
【发布时间】:2019-10-05 21:18:55
【问题描述】:

我有一个混合的 TS/JS 项目 - 最终我们将采用完整的 TS,但现在还有很长的路要走。

与此同时,我们在 JS 文件中使用了 // @ts-check 指令和 <script> 标签,它们非常强大。

我想在 JS 文件中引用一些 TS 定义,如下所示:

// @ts-check
/// <reference path="MyInterface.d.ts" />

/** @type {MyInterface}  */
let x = ...

只有这不起作用 - TS 类型检查(以及 VS2017 的智能感知)认为 xany

我想要 x 上的类型定义的智能感知,并在调用 x.propNameMyInterface 没有 propName 时发出警告。

我知道我可以用 JS 文档 @typedef 替换 &lt;reference path="MyInterface.d.ts" /&gt;,但我有很多定义文件,不希望重复定义。

有没有办法让@ts-check 引用.d.ts 文件?

【问题讨论】:

  • 您的定义文件中是否有导入? That requires some extra declarations.
  • @Aankhen 是的,我们在 TS derective 文件中广泛使用 ES6 import,但在 JS 中没有。我会试试看。
  • @Aankhen 试过了 - 它不起作用。我们不希望每个.d.ts 定义都成为全局的,每个都包含特定的exportexport default 指令——在@ts-check 引用中,该类始终是默认值,因此在MyInterface.d.ts 中我们同时拥有export interface MyInterfaceexport default MyInterface,这样import { MyInterface } ...import MyInterface ... 都可以工作。
  • 明白了。不幸的是,没有其他想法。

标签: javascript typescript jsdoc


【解决方案1】:

official recommendation 是使用导入类型:

// @ts-check

/** @type {import("./MyInterface").MyInterface} */
let x = ...;

或者,您可以使用@typedef 为导入的类型指定名称:

// @ts-check

/** @typedef {import("./MyInterface").MyInterface} MyInterface

/** @type {MyInterface} */
let x = ...;

【讨论】:

  • 这行得通,也是我第一次遇到 JSDoc @type derectives 的语法(它看起来像没有 await 的 ES6 动态 import)。确实需要有人将其添加到某处的某些文档中。
猜你喜欢
  • 2018-07-29
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
  • 2019-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多