在JavaScript的类型输入文件中声明接口 [英] Declare Interfaces in typings file for JavaScript

查看:129
本文介绍了在JavaScript的类型输入文件中声明接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个利用.d.ts文件的JavaScript项目.这是我先前提出的问题的后续问题,因此您可以查看有关项目的更多信息

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 regarding the project here.

尽管我通常可以从类型文件中提取函数,但是我不能提取为空或仅由接口组成的接口或名称空间.我已经通过为每个接口创建一个const实现并在注释中使用@typeof ConstantImplementation来临时解决此问题.请参见下面的示例:

Although I can normally extract functions from the typings files I can't extract interfaces or namespaces that are either empty or consist purely of interfaces. I have temporarily fixed this problem by creating a const implementation for each interface and using @typeof ConstantImplementation in the comments. See Example below:

// Typings File
export namespace test {
    export interface ITest {
        foo: string;
        bar: number;
    }
    export const Test: ITest;
}


// JS File
if (undefined) var {Test: ITest} = require("globals.d.ts").test; 
// Above line shows `unused var error`

/* @type {typeof ITest} */
var x = {};
x.foo = "hello";
x.bar = 3;
// if I do `x.` intellisense should suggest `foo` and `bar` 

我想知道是否有更好的方法来解决该问题,最好是一种不会引发错误的方法(使用eslint ignore line不能解决问题).

I was wondering if there is a better way to go around the problem, preferably one that doesn't throw an error (using eslint ignore line isn't a fix).

此问题与从打字文件获取功能无关.纯粹是要使VSCode智能感知与类型输入接口一起使用.这是一张图片,解释我想要的是什么(圆圈内的两行):

This question is not about getting functionality from typings file. It's purely about making VSCode intellisense working with typings Interfaces. Here is an image to explain what it is that I want (the two lines inside the circle):

推荐答案

因此我能够使用JSDoc解决问题

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.

智能感知现在起作用

我发现的另一件事是,如果您将

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

jsconfig.json

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

您的智能感知将进一步提高

Your intellisense improves further

Update-1

如@nickzoum所指出的,如果您按以下方式定义test.d.ts

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;

然后,您还可以在JS中使用以下表单进行智能操作

Then you can also use below form in JS for intellisense

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

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

这篇关于在JavaScript的类型输入文件中声明接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆