[英]Declare Interfaces in typings file for JavaScript
我正在使用.d.ts
文件的JavaScript项目。 这是我先前提出的问题的后续问题,因此您可以在此处查看有关该项目的更多信息。
尽管我通常可以从类型文件中提取函数,但是我不能提取为空或仅由接口组成的接口或名称空间。 我已通过为每个接口创建const
实现并在注释中使用@typeof ConstantImplementation
来临时解决此问题。 请参见下面的示例:
// 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
不是解决方案)。
这个问题与从打字文件获取功能无关。 纯粹是要使VSCode智能感知与类型接口一起使用。 这是一张图片,解释我想要什么(圆圈内的两行):
我认为可能存在概念上的误解,这是您在此处遇到的问题的基础。 听起来您希望这些接口在运行时可用。 Typescript接口纯粹是一个编译时概念。 他们不编译任何东西。 它们在运行时不存在。
我将您的代码的这一部分放入了一个名为interf.d.ts
的文件中:
export namespace Interfaces {
export interface Interface {
property: string;
}
}
然后我创建了文件test.ts
:
import { Interfaces } from "./interf";
const x: Interfaces.Interface = {
property: "abc",
};
console.log(x);
我没有编译错误,并且执行得很好。 如预期的那样,接口已导出。 该const
你以后出口不需要导出接口(反正它不出口的接口,它导出一个const
,其声明,以符合接口,但const
不是接口)。
但是,如果您试图在已编译的JavaScript中找到与您的接口相对应的内容,则由于我上面给出的原因,您将找不到它:它是一个编译时构造。
所以我能够使用JSDoc解决问题
测试文件
export namespace test {
export interface ITest {
foo: string;
bar: number;
}
}
test.js
/**
* @type {import("./test").test.ITest}
*/
let x;
x.
而智能感知现在
我发现的另一件事是,如果您添加jsconfig.json
与
jsconfig.json
{
"compilerOptions": {
"checkJs": true
}
}
您的智商进一步提高
更新1
正如@nickzoum所指出的,如果您定义test.d.ts
如下
export interface ITest {
foo: string;
bar: number;
}
export as namespace test;
然后您也可以在JS中使用以下形式进行智能感知
/** @typedef {import("./test").ITest} ITest */
/** @type {ITest} */
var x = {};
x.
我发现无需任何额外配置并且使用简单即可运行的某些东西,但是您需要配置tsconfig.json。
tsconfig.json
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"moduleResolution": "node",
"baseUrl": "../",
"noEmit": true,
"target": "es5"
}
}
测试文件
export = Test
export as namespace Test
declare namespace Test {
interface ITest {
foo: string;
bar: number;
}
}
test.js
/**
* @type {Test.ITest}
*/
let x;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.