Arrow type
- TypeScript course
- Beginner
- Lesson 49/89
- 4 min
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); // 6A function type clarifies the callback's signature.
Practice 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.
Starter code
// uygula adında bir fonksiyon tanımla
// islem parametresi (x: number) => number türünde, deger parametresi number olsun
// islem(deger) değerini döndür
// ikiyle adında bir ok fonksiyonu tanımla (x * 2 döndürsün)
// uygula(ikiyle, 5) sonucunu yazdırSample 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));Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
Explanation: 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.
2 Complete the function type
let islem: (x: number) => ____ = (x: number): number => x + 1;
let islem: (x: number) => number = (x: number): number => x + 1;
Explanation: Since the function on the right returns <code>x + 1</code> (a number), the return part of the type must be <code>number</code>. <code>string</code>, <code>void</code> and <code>boolean</code> are wrong return types.
3 Arrow type concepts
| Term | Meaning |
|---|---|
(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 |