1

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.

Is there anything I can do about it ?

In case of need, the library is markdown-pdf.

1 Answer 1

1

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

Playground link

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

Playground link

Sign up to request clarification or add additional context in comments.

1 Comment

Oh for sure ! I forgot about intersection type because it was a function, but yeah, a function is a type to. Thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.