Search code examples
javascripttypescriptkotlin-js

How to use/import TypeScript declaration files in JavaScript?


I'm playing a little bit with Kotlin Multiplatform.

Right now, I try to develop a Kotlin JS library to import and use it in an external JavaScript project. This works fine so far. 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.

But my IDE shows that there is an unresolved function or method:

unresolved function or method

I'm new to JavaScript and was wondering about this warning because it works.

So I searched and found this:

The Kotlin/JS IR compiler is capable of generating TypeScript definitions from your Kotlin code. 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

I assume that I need these TypeScript definitions to tell my IDE that this method exists.

Hours later, I got how to tell the Kotlin compiler(?) to generates this definition, but the warning is still there :-(

The generated shared.d.ts file looks like this:

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;

This is the generated package.json file:

{
  "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>".

I also found this question How to use TypeScript declaration files alongside JavaScript, but maybe I'm not able to follow the answer, or it doesn't solve my problem.

Is there a way to tell the IDE that this method exists? Should this TypeScript declaration file solve it? And if yes, how do I use/import it?


Solution

  • The following works at least for IntelliJ IDEA Ultimate:

    Adding "@types/shared": "file:../blh_shared/build/js/packages/shared" to the package.json file of my React project adds code completion in my IDE.

    The package.json file now looks like this:

    {
      "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",
      }
    }