[英]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.