[英]Defining types for untyped module that exports single function
I am using parse-diff
in a TypeScript project. 我在TypeScript项目中使用
parse-diff
。 parse-diff
does not contain a type definition, so I went about writing my own. parse-diff
不包含类型定义,因此我开始编写自己的类型。
It exports a single function, like this: 它导出单个函数,如下所示:
exports = function () { /* ... */ }
and I include it in the script as: 我将其包含在脚本中为:
import * as parse from 'parse-diff';
I got the definition to work by declaring a module. 我通过声明一个模块来使定义生效。 This is what I've got so far:
到目前为止,这是我得到的:
declare module 'parse-diff' {
interface Change {
type: string;
normal: boolean;
ln1: number;
ln2: number;
content: string;
}
interface Chunk {
content: string;
changes: Change[];
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
}
interface File {
chunks: Chunk[];
deletions: number;
additions: number,
from: string,
to: string,
index: string[]
}
function parse(diff: string): File[];
namespace parse {}
export = parse;
}
This works fine. 这很好。 The problem now is that I can't figure out how I could import and use the individual interfaces elsewhere.
现在的问题是,我无法弄清楚如何导入和使用其他地方的各个接口。
If I import them from the package, I get the error: 如果从包中导入它们,则会出现错误:
"parse-diff" has no export member "File"
“ parse-diff”没有导出成员“文件”
If I export
the interfaces from the module, I'd have to export default
the parse
function. 如果我从模块中
export
接口,则必须export default
的parse
函数。 That way I get the error: 这样我得到错误:
Cannot invoke an expression whose type lacks a call signature.
无法调用类型缺少调用签名的表达式。 Type 'typeof 'parse-diff'' has no compatible call signatures.
类型'typeof'parse-diff'没有兼容的呼叫签名。
I just can't figure out how I can keep the "only one export" nature of the module and also use the internal interfaces. 我只是想不通如何保持模块的“仅一次导出”性质并使用内部接口。
Edit your namespace and declare the interfaces inside it 编辑您的名称空间并声明其中的接口
declare module "parse-diff" {
function parse(diff: string): parse.File[];
namespace parse {
interface Change {
type: string;
normal: boolean;
ln1: number;
ln2: number;
content: string;
}
interface Chunk {
content: string;
changes: Change[];
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
}
interface File {
chunks: Chunk[];
deletions: number;
additions: number;
from: string;
to: string;
index: string[];
}
}
export = parse;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.