Callable
You can annotate callables as a part of a type or an interface as follows
interfaceReturnString { ():string}An instance of such an interface would be a function that returns a string e.g.
declareconstfoo:ReturnString;constbar=foo();// bar is inferred as a stringObvious examples
Of course such acallable annotation can also specify any arguments / optional arguments / rest arguments as needed. e.g. here is a complex example:
interfaceComplex { (foo:string, bar?:number,...others:boolean[]):number;}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 ofany 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 anumber and returns astring 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 ofcallable type annotation with the prefixnew. It simply means that you need toinvoke withnew e.g.
Last updated