[英]Create type definition for function returning the module itself
有一個看起來像這樣的nodejs模塊
module.exports = {
init(arg1) {
// ..
return this;
},
// ..
};
我正在嘗試編寫定義文件。 看起來像這樣
declare namespace ModuleName {
function init(smth: string): ModuleName;
}
export = ModuleName;
export as namespace ModuleName;
}
它幾乎可以工作。 當我導入它時
const a = require('ModuleName');
VSCode 理解a.init
是一個 function 接受一個字符串參數。 但我無法理解結果也有可以調用的方法init
。 即
const b = a.init('smth');
b.init('smth2');
在這種情況下編寫類型定義的正確方法是什么?
我發現只有通過接口的方法,但不確定。
declare namespace ModuleName {
interface IModuleName {
init(s: string): IModuleName;
}
function init(s: string): IModuleName;
}
const m = require('ModuleName');
const a = m.init('a');
const b = a.init('b');
或者更短
interface ModuleName {
init(s: string): ModuleName;
}
const m: ModuleName = require('./ModuleName');
const a = m.init('a');
const b = a.init('b');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.