As you navigate through the collections typings file, a common pattern emerges:
interface Set<T> {
add(value: T): this;
clear(): void;
delete(value: T): boolean;
forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
readonly size: number;
}
interface SetConstructor {
new (): Set<any>;
new <T>(values?: T[]): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
This structure includes:
- An interface for a collection type
- A constructor interface
- And a variable declared with
declare
The perplexity arises. Could someone provide clarity by answering these questions?
- The role of
Set<T>
appears straightforward, but where is the actual implementation? When callingnew Set()
, what exactly is being instantiated? In contrast to other languages where interfaces cannot be directly instantiated, only classes implementing them. - What purpose does the set constructor interface serve? Since it's not a class, it doesn't seem to contain executable code.
- The use of
declare var
adds further confusion:Declare
typically introduces types implemented elsewhere. How can a variable fall into this category? Shouldn'timport
(orrequire
) fulfill the role of importing external implementations?- The naming similarity between the Set interface and the declared variable raises questions about potential conflicts. How do they coexist without issue?
- The "combining" aspect between the two interfaces (
Set
for name andSetConstructor
for type) is puzzling—what exactly is its purpose?