Return type annotation
- TypeScript course
- Beginner
- Lesson 32/89
- 4 min
Learn to explicitly write function return types.
Return type annotation
To specify a function's return type explicitly, you write : type after the parameter list and before the opening brace. This guarantees the function always returns the correct type.
function topla(a: number, b: number): number {
return a + b;
}A return type annotation catches returning the wrong type at compile time.
Return type and inference
If no return type is declared, TypeScript infers it from the return statement. But an explicit return type clarifies the function's contract and prevents future changes from returning the wrong type.
function selam(isim: string): string {
return "Merhaba " + isim;
}An explicit return type is especially recommended for public functions.
Practice Write a function with a return type
Define a function named kare with an x parameter of type number and return type number. The function should return x * x. Print the result of calling kare(6) with console.log.
Starter code
// kare adında bir fonksiyon tanımla
// x parametresi number, dönüş türü number olsun
// x * x değerini döndür
// kare(6) sonucunu yazdırSample solution
function kare(x: number): number {
return x * x;
}
console.log(kare(6));Expected output
36
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In <code>function f(x: number): string</code>, where is the return type?
- Before the function name
- After the parameter list, before the brace Correct answer
- Inside the function body
- After the return statement
Explanation: The return type <code>: string</code> is written after the parameter list's closing parenthesis and before the opening brace.
2 Add the return type
function selam(isim: string): ____ { return "Merhaba " + isim; }
function selam(isim: string): string { return "Merhaba " + isim; }
Explanation: The function returns <code>"Merhaba " + isim</code>, which is a string, so the return type must be <code>string</code>. <code>number</code>, <code>void</code> and <code>boolean</code> are wrong types.
3 Return type concepts
| Term | Meaning |
|---|---|
: number (süslü parantezden önce) |
Return type declaration |
function f(): string |
Function returning a string |
function f(): void |
Return without a value |
Return type annotation |
Specifying what a function returns |