Ambient Classes and Functions Can Merge
In previous versions of TypeScript, it was an error to merge classes and functions under any circumstances.Now, ambient classes and functions (classes/functions with the declare
modifier, or in .d.ts
files) can merge.This means that now you can write the following:
export declare function Point2D(x: number, y: number): Point2D;
export declare class Point2D {
x: number;
y: number;
constructor(x: number, y: number);
}
instead of needing to use
export interface Point2D {
x: number;
y: number;
}
export declare var Point2D: {
(x: number, y: number): Point2D;
new (x: number, y: number): Point2D;
}
One advantage of this is that the callable constructor pattern can be easily expressed while also allowing namespaces to merge with these declarations (since var
declarations can’t merge with namespace
s).
In TypeScript 3.7, the compiler will take advantage of this feature so that .d.ts
files generated from .js
files can appropriately capture both the callability and constructability of a class-like function.
For more details, see the original PR on GitHub.