Advertisement
Advanced TypeScript, Declaration Files

How do you write a declaration file for a library with multiple overloaded call signatures, like jQuery's $()?

Short answer

List multiple function signatures back-to-back with the same name (no implementation) inside the declaration file — TypeScript treats them as overloads and picks the most specific matching signature based on the caller's argument types.

Save TypeScript mock interview
Advertisement
AModel answer
List multiple function signatures back-to-back with the same name (no implementation) inside the declaration file — TypeScript treats them as overloads and picks the most specific matching signature based on the caller's argument types.
declare function $(selector: string): HTMLElement[];
declare function $(callback: () => void): void;

$('#app');           // resolves to the string overload
$(() => console.log('ready')); // resolves to the callback overload
Real-world example
Accurately describing a flexible, multi-shape JavaScript API in a hand-written declaration file for a legacy library.
Likely follow-ups
  • How does overload resolution differ when writing overloads in a declaration file versus in a regular implementation function?
Related topics