23.06.2015 Views

TypeScript Language Specification v1.5

TypeScript Language Specification v1.5

TypeScript Language Specification v1.5

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Interface definitions, like the one above, can have one or more type parameters. In this case the 'Array'<br />

interface has a single parameter, 'T', that defines the element type for the array. The 'reverse' method<br />

returns an array with the same element type. The sort method takes an optional parameter, 'compareFn',<br />

whose type is a function that takes two parameters of type 'T' and returns a number. Finally, sort returns<br />

an array with element type 'T'.<br />

Functions can also have generic parameters. For example, the array interface contains a 'map' method,<br />

defined as follows:<br />

map(func: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];<br />

The map method, invoked on an array 'a' with element type 'T', will apply function 'func' to each element<br />

of 'a', returning a value of type 'U'.<br />

The <strong>TypeScript</strong> compiler can often infer generic method parameters, making it unnecessary for the<br />

programmer to explicitly provide them. In the following example, the compiler infers that parameter 'U' of<br />

the map method has type 'string', because the function passed to map returns a string.<br />

function numberToString(a: number[]) {<br />

var stringArray = a.map(v => v.toString());<br />

return stringArray;<br />

}<br />

The compiler infers in this example that the 'numberToString' function returns an array of strings.<br />

In <strong>TypeScript</strong>, classes can also have type parameters. The following code declares a class that implements<br />

a linked list of items of type 'T'. This code illustrates how programmers can constrain type parameters to<br />

extend a specific type. In this case, the items on the list must extend the type 'NamedItem'. This enables<br />

the programmer to implement the 'log' function, which logs the name of the item.<br />

interface NamedItem {<br />

name: string;<br />

}<br />

class List {<br />

next: List = null;<br />

constructor(public item: T) {<br />

}<br />

insertAfter(item: T) {<br />

var temp = this.next;<br />

this.next = new List(item);<br />

this.next.next = temp;<br />

}<br />

13

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

Saved successfully!

Ooh no, something went wrong!