Skip to content Skip to sidebar Skip to footer

Declare Interfaces In Typings File For JavaScript

Project Info I'm working on a JavaScript project that utilizes .d.ts files. This is a subsequent question to a question I previously asked, so you can view more information regardi

Solution 1:

So I was able to solve the issue using JSDoc

test.d.ts

export namespace test {
    export interface ITest {
        foo: string;
        bar: number;
    }
}

test.js

/**
 * @type {import("./test").test.ITest}
 */

let x;

x.

And the intellisense works nows

Working intellisense

Also one thing I found is that if you add jsconfig.json with

jsconfig.json

{
    "compilerOptions": {
        "checkJs": true
    }
}

Your intellisense improves further

Better intellisense

Update-1

As pointed out by @nickzoum, if you define the test.d.ts like below

export interface ITest {
    foo: string;
    bar: number;
}

export as namespace test;

Then you can also use below form in JS for intellisense

/** @typedef {import("./test").ITest} ITest */

/** @type {ITest} */
var x = {};
x.

Solution 2:

I'm thinking there may be a conceptual misunderstanding that underlies your problem here. It sounds like you want the interfaces to be available at runtime. Typescript interfaces are purely a compile-time concept. They do no compile to anything. They have no existence at runtime.

I took this part of your code and put it in a file named interf.d.ts:

export namespace Interfaces {
    export interface Interface {
        property: string;
    }
}

Then I created the file test.ts:

import { Interfaces } from "./interf";

const x: Interfaces.Interface = {
    property: "abc",
};

console.log(x);

I get no compilation error, and it executes just fine. As expected, the interface is exported. The const you export later is not needed to export the interface (and anyway it does not export an interface, it exports a const which is declared to conform to the interface, but the const is not the interface).

However, if you're trying to find something in the compiled JavaScript that corresponds to your interface, you won't find it, for the reason I gave above: it is a compile-time construct.


Solution 3:

I found something that is working without any extra configuration and with a simple usage, but you need to configure a tsconfig.json.

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": true,
    "moduleResolution": "node",
    "baseUrl": "../",
    "noEmit": true,
    "target": "es5"
  }
}

test.d.ts

export = Test
export as namespace Test
declare namespace Test {
  interface ITest {
    foo: string;
    bar: number;
  }
}

test.js

/**
 * @type {Test.ITest}
 */
let x;

Post a Comment for "Declare Interfaces In Typings File For JavaScript"