04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 22: The Evolution of JavaScript<br />

Function Types<br />

You can also specify function types, which specify the type and number of arguments expected as well<br />

as the return type. This can be useful for functions that accept callback functions as arguments, as in this<br />

example:<br />

type Callback = function(int, string): void;<br />

function doSomething(callback: Callback) {<br />

callback(0, “Success”)<br />

}<br />

Here, a Callback type is defined to be a function that accepts two arguments: an int and a string .<br />

The function shouldn ’ t return a value, so the return value is specified as void . You can specify that an<br />

argument is optional by appending an equal sign as shown here:<br />

type Callback = function(int, string=): void;<br />

//second argument optional<br />

The Callback type now optionally accepts a second argument that ’ s a string .<br />

A function type can specify a method on a given type of object by specifying the type that this<br />

should be, as in this example:<br />

type Callback = function(this: Person, string): void; //method on a Person<br />

Here, the Callback type defines a function that must be a method of a Person object and accepts a<br />

single string argument.<br />

The last option is to specify that there may be rest arguments to the function. This can be done using<br />

three dots to specify any arguments or three dots followed by a type in square braces to indicate that the<br />

arguments must be of a specific type. Here’s an example:<br />

type SomeFunction = function(string,...): boolean<br />

type MyFunction = function(string,...[string]): boolean<br />

The first type, SomeFunction , specifies a function that accepts a string as its first argument and then a<br />

variable number of arguments that can be any type. The second type, MyFunction , is the same except<br />

that the rest arguments must be of the type string .<br />

Parameterized Types<br />

Parameterized types can be used when a type should have a certain structure but the data types in that<br />

structure may change, as in this example:<br />

type Point. < T > = {<br />

x: T,<br />

y: T<br />

};<br />

724

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!