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.

An example:<br />

signature are fixed, and e's type is changed to a function type with e's call signature instantiated<br />

in the context of T's call signature (section 3.10.5).<br />

function choose(x: T, y: T): T {<br />

return Math.random() < 0.5 ? x : y;<br />

}<br />

var x = choose(10, 20); // Ok, x of type number<br />

var y = choose("Five", 5); // Error<br />

In the first call to 'choose', two inferences are made from 'number' to 'T', one for each parameter. Thus,<br />

'number' is inferred for 'T' and the call is equivalent to<br />

var x = choose(10, 20);<br />

In the second call to 'choose', an inference is made from type 'string' to 'T' for the first parameter and an<br />

inference is made from type 'number' to 'T' for the second parameter. Since neither 'string' nor 'number' is<br />

a supertype of the other, type inference fails. That in turn means there are no applicable signatures and<br />

the function call is an error.<br />

In the example<br />

function map(a: T[], f: (x: T) => U): U[] {<br />

var result: U[] = [];<br />

for (var i = 0; i < a.length; i++) result.push(f(a[i]));<br />

return result;<br />

}<br />

var names = ["Peter", "Paul", "Mary"];<br />

var lengths = map(names, s => s.length);<br />

inferences for 'T' and 'U' in the call to 'map' are made as follows: For the first parameter, inferences are<br />

made from the type 'string[]' (the type of 'names') to the type 'T[]', inferring 'string' for 'T'. For the second<br />

parameter, inferential typing of the arrow expression 's => s.length' causes 'T' to become fixed such that<br />

the inferred type 'string' can be used for the parameter 's'. The return type of the arrow expression can<br />

then be determined, and inferences are made from the type '(s: string) => number' to the type '(x: T) =><br />

U', inferring 'number' for 'U'. Thus the call to 'map' is equivalent to<br />

var lengths = map(names, s => s.length);<br />

and the resulting type of 'lengths' is therefore 'number[]'.<br />

In the example<br />

70

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

Saved successfully!

Ooh no, something went wrong!