Product docs and API reference are now on Akamai TechDocs.
Search product docs.
Search for “” in product docs.
Search API reference.
Search for “” in API reference.
Search Results
 results matching 
 results
No Results
Filters
Getting Started with TypeScript Functions
Traducciones al EspañolEstamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
Declaring Functions
JavaScript supports both named and anonymous functions, and TypeScript inherits this syntax. The example below shows two ways you can create functions in JavaScript and TypeScript. To create a function use the function
keyword and enclose the body of the function in curly brackets.
- File: function_example.ts
1 2 3 4 5 6 7 8 9
// Named function function add(x, y) { return x + y; } // Anonymous function let myAdd = function (x, y) { return x + y; };
Using TypeScript Types to Catch Bugs in Functions
Adding type annotations using TypeScript can make a huge difference in the stability of JavaScript code. Instead of hiding until run-time, many errors show up while editing with TypeScript supported editors, or during the compilation phase. For example, consider a simple function to convert degrees Fahrenheit to Celsius.
- File: example_function.ts
1 2 3
function FtoC (f) { return (f - 32.) * 5. / 9. }
In the example above, the f
parameter’s type is any
by default. This means you can call this function with any kind of value, for instance:
- File: example_function.ts
1 2 3 4 5 6
function FtoC (f) { return (f - 32.) * 5. / 9. } FtoC(32); // number FtoC("hello"); // string
The FtoC()
function should not accept a value of type string
. When declaring your function, you can assign the number
type to the parameter. Doing so means that an error is generated when calling the FtoC()
function with a parameter of type string
.
- File: example_function.ts
1 2 3 4 5 6
function FtoC (f: number) { return (f - 32.) * 5. / 9. } FtoC(32); FtoC("hello");
You don’t need to annotate the return type, because the TypeScript compiler infers the correct type, number
.
In a TypeScript supported editor such as Visual Studio Code, or in the tsc compiler, the second call, FtoC("hello");
now generates an error message:
Argument of type 'string' is not assignable to parameter of type 'number'.ts(2345)
NaN
when it tries to perform arithmetic, since “hello” is not a number, and the call returns undefined
.Using Generics
If you write a function with no type attributes, then the attribute types default to any
. This can be convenient when a function’s attribute types are not important. However, it may make things harder when you have code that needs to consume the function’s return value.
A way around this it o use generics
. Generics are expressed with angle brackets, denoted by the type variable <Type>
. You can use generics to tie the type of one value to another, as in the example below from the TypeScript documentation.
- File: generics_example.ts
1 2 3 4 5 6 7 8 9
function firstElement<Type>(arr: Type[]): Type { return arr[0]; } // s is of type 'string' const s = firstElement(["a", "b", "c"]); // n is of type 'number' const n = firstElement([1, 2, 3]);
In this example, TypeScript infers the type of <Type>
from the input array and propagates that to the return value. ["a", "b", "c"]
is an array of strings, so s
is a string. [1, 2, 3]
is an array of numbers, so n
is a number.
Optional Parameters
JavaScript lets you assign default values to function parameters. This makes the parameters optional when calling the function. TypeScript also lets you declare optional parameters without setting their default values. This is done by adding a ?
after the variable name, as shown in the example below:
- File: optional_params_example.ts
1 2 3 4 5
function f(x?: number) { console.log(typeof x, x) } f(); // OK f(10); // OK
Function Overloads
With function overloads you can call a single function in different ways. However, writing good function overloads is tricky, since the implementation overload has to be compatible with all the overload signatures.
- File: function_overload_example.ts
1 2 3 4 5
function len(s: string): number; function len(arr: any[]): number; function len(x: any) { return x.length; }
The function overloads in the example above can handle strings or arrays. Before writing function overloads, consider writing a function with union types for arguments, as shown in the following example:
- File: function_overload_example.ts
1 2 3
function len(x: any[] | string) { return x.length; }
Further Information
To learn more about functions, visit the More on Functions page in the TypeScript documentation. You can also visit the TypeScript playground to get some hands-on practice.
This page was originally published on