Module declaration with same name for property and function

Clash Royale CLAN TAG#URR8PPP
Module declaration with same name for property and function
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.
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
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:
FromOptionsBuilder
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:
from
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
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Oh for sure ! I forgot about intersection type because it was a function, but yeah, a function is a type to. Thanks !
– MonsieurMan
Aug 6 at 8:29