繁体   English   中英

如何在 JavaScript 中使用/导入 TypeScript 声明文件?

[英]How to use/import TypeScript declaration files in JavaScript?

我正在玩一点 Kotlin Multiplatform。

现在,我尝试开发一个 Kotlin JS 库来导入并在外部 JavaScript 项目中使用它。 到目前为止,这工作正常。 Kotlin creates the JavaScript files from the Kotlin code, I can import and use them in the JavaScript project, and it does what it should.

但是我的 IDE 显示有一个未解决的 function 或方法:

未解决的功能或方法

我是 JavaScript 的新手,我想知道这个警告,因为它有效。

所以我搜索并发现了这个:

Kotlin/JS IR 编译器能够从您的 Kotlin 代码生成 TypeScript 定义。 These definitions can be used by JavaScript tools and IDEs when working on hybrid apps to provide autocompletion, support static analyzers, and make it easier to include Kotlin code in JavaScript and TypeScript projects. https://kotlinlang.org/docs/reference/js-ir-compiler.html#preview-generation-of-typescript-declaration-files-dts

我假设我需要这些 TypeScript 定义来告诉我的 IDE 这种方法存在。

几小时后,我知道如何告诉 Kotlin 编译器(?)生成这个定义,但警告仍然存在:-(

生成的shared.d.ts文件如下所示:

type Nullable<T> = T | null | undefined
export namespace api.model {
    class AuthResponse {
        // lots of code
    }
}
export namespace api {
    function requestToken(): kotlin.js.Promise<api.model.AuthResponse>;
}
export as namespace shared;

这是生成的package.json文件:

{
  "main": "kotlin/shared.js",
  "devDependencies": {
    "webpack": "4.44.1",
    "webpack-cli": "3.3.12",
    "source-map-loader": "1.0.1",
    "dukat": "0.5.8-rc.3"
  },
  "dependencies": {
    // kotlin related imports
  },
  "peerDependencies": {},
  "optionalDependencies": {},
  "bundledDependencies": [],
  "name": "shared",
  "version": "1.0.0"
}

In the JavaScript project, I added this line to the package.json file "shared": "file:..<path to the other package.json file>" .

我还发现了这个问题How to use TypeScript 声明文件以及 JavaScript ,但也许我无法遵循答案,或者它不能解决我的问题。

有没有办法告诉 IDE 这种方法存在? 这个 TypeScript 声明文件应该解决吗? 如果是,我该如何使用/导入它?

简单来说,就是使用typescript声明文件让typescript理解JS。 不是反过来。 .d.ts文件仅在 TypeScript 项目中有用,它允许 TypeScript 对 JavaScript 模块进行类型推断。

如果您想解决警告,请在您的 JS 项目中导入shared.js文件。

以下至少适用于 IntelliJ IDEA Ultimate:

添加"@types/shared": "file:../blh_shared/build/js/packages/shared"到我的 React 项目的package.json文件中添加代码完成在我的 Z581D6381F3F38E4BF364

package.json文件现在如下所示:

{
  "name": "react_app",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "shared": "file:../blh_shared/build/js/packages/shared",
  },
  "devDependencies": {
    "@types/shared": "file:../blh_shared/build/js/packages/shared",
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM