An interface can provide multiple callable annotations to specify function overloading. For example:
interfaceOverloaded{(foo:string):string(foo:number):number}// example implementationfunctionstringOrNumber(foo:number):number;functionstringOrNumber(foo:string):string;functionstringOrNumber(foo:any):any{if (typeof foo ==='number') {return foo * foo;}elseif (typeof foo ==='string') {return`hello ${foo}`;}}constoverloaded:Overloaded= stringOrNumber;// example usageconststr=overloaded('');// type of `str` is inferred as `string`constnum=overloaded(123);// type of `num` is inferred as `number`
Of course, like the body of any interface, you can use the body of a callable interface as a type annotation for a variable. For example:
Arrow Syntax
To make it easy to specify callable signatures, TypeScript also allows simple arrow type annotations. For example, a function that takes a number and returns a string can be annotated as:
Only limitation of the arrow syntax: You can't specify overloads. For overloads you must use the full bodied { (someArgs): someReturn } syntax.
Newable
Newable is just a special type of callable type annotation with the prefix new. It simply means that you need to invoke with new e.g.
interface CallMeWithNewToGetString {
new(): string
}
// Usage
declare const Foo: CallMeWithNewToGetString;
const bar = new Foo(); // bar is inferred to be of type string