TypeScript
Arrow type
Learn to use arrow functions as types.
Arrow type
Arrow function syntax can also express a function type. (x: number) => number is a function type that takes and returns a number. This is useful for callbacks and function parameters.
let islem: (x: number) => number =
(x: number): number => x * 2;
The left side is the type, the right side is the value.
Callbacks with function types
Function types are useful for parameters that accept callbacks. You can pass any function matching the signature. This makes passing functions as parameters safe.
function uygula(f: (x: number) => number, n: number): number {
return f(n);
}
uygula((x: number): number => x + 1, 5); // 6
A function type clarifies the callback's signature.
Exercise Use a function type with a callback
Define a function named uygula with islem: (x: number) => number and deger: number parameters and return type number. The function should return islem(deger). Define an arrow function named ikiyle ((x: number): number => x * 2). Print the result of calling uygula(ikiyle, 5) with console.log.
Show example solution
function uygula(islem: (x: number) => number, deger: number): number {
return islem(deger);
}
const ikiyle = (x: number): number => x * 2;
console.log(uygula(ikiyle, 5));
Test yourself
-
What does <code>(x: number) => number</code> describe as a type?
- A number variable
- An arrow function expression
- A function call
- A function type taking and returning a number
Show answer
A function type taking and returning a number — In a type context, <code>(x: number) => number</code> describes the type of functions that take a number parameter and return a number; it is used in a type context, not a value context.
-
Complete the function type
let islem: (x: number) => ____ = (x: number): number => x + 1;
Show answer
let islem: (x: number) => number = (x: number): number => x + 1;
-
Arrow type concepts
- (x: number) => number
- Type taking and returning number
- Function type
- Function signature as a type
- Callback
- Function as a function parameter
- Arrow type
- Type declaration with arrow syntax
Next lesson: Summary - Arrow functions