属性和函数同名的模块声明 [英] Module declaration with same name for property and function

查看:30
本文介绍了属性和函数同名的模块声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为公开以下 API 的现有功能模块库编写定义:

I am writing definitions for an existing function module library which exposes the following API:

fn().from(opts: Options)
// and
fn().from.string(path: String)

我在此处找到了有关声明合并的信息.它说的是多次为重载声明一个同名的函数.但它没有说明为位于同一位置的函数和属性编写类型.

I found about declaration merging here. Where it says something about declaring many times a function with the same name for overloads. But it says nothing about writing types for a function and a property living in the same place.

尽管如此,我还是试着写了:

Nevertheless I tried writing:

export interface Test {
    from(path: string): ToOptionsBuilder;
}
export interface Test {
    from: FromOptionsBuilder;
}

但正如预期的那样,编译器抱怨:后续的属性声明必须具有相同的类型.

But as expected, the compiler complains: Subsequent property declarations must have the same type.

有什么我可以做的吗?

如果需要,库是markdown-pdf.

推荐答案

您不能对字段使用声明合并.您可以通过使用函数签名和 FromOptionsBuilder 接口之间的交集类型来声明该字段以符合您想要的声明:

You can't use declaration merging for a field. You can declare the field to conform to the declaration you want by using an intersection type between a function signature and the FromOptionsBuilder interface:

export interface Test {
    from: FromOptionsBuilder & {
        (path: string): ToOptionsBuilder;
    };
}

//Test
interface FromOptionsBuilder { fromField : number }
interface ToOptionsBuilder { toField: number}
declare let t: Test;
t.from.fromField
t.from("").toField

游乐场链接

如果您希望模块的用户能够向 from 函数添加重载,您可以使用一个额外的接口作为其他人可以合并其重载的接口:

If you want users of the module to be able to add overloads to the from function, you can use an extra interface to be the interface others can merge their overloads in:

export interface Test {
    from: IFormFunction
}

export interface IFormFunction extends FromOptionsBuilder {
    (path: string): ToOptionsBuilder;
}
//Extended overload 
export interface IFormFunction  {
    (path: string, otherValue: string): ToOptionsBuilder;
}
//Test
interface FromOptionsBuilder { fromField : number }
interface ToOptionsBuilder { toField: number}
declare let t: Test;
t.from.fromField
t.from("").toField
t.from("", "").toField

游乐场链接

这篇关于属性和函数同名的模块声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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