Parameter annotation
- TypeScript course
- Beginner
- Lesson 31/89
- 4 min
Learn to type function parameters.
Parameter annotation
By giving function parameters explicit types, you ensure that only values of the correct type can be passed. Each parameter gets : type after its name. Functions without parameter type annotations have parameters that are implicitly any.
function topla(a: number, b: number) {
return a + b;
}Parameter annotations prevent passing the wrong type of data to a function.
Multiple parameter annotations
Each parameter gets its own type; : type is written after each comma-separated name. This lets each argument be checked separately at the call site.
function bilgi(isim: string, yas: number, aktif: boolean) {
console.log(isim, yas, aktif);
}Giving each of multiple parameters a separate type clarifies the function's contract.
Practice Write a function with typed parameters
Define a function named topla with a and b parameters of type number. The function should return a + b. Print the result of calling topla(3, 7) with console.log.
Starter code
// topla adında bir fonksiyon tanımla
// a ve b parametreleri number olsun
// a + b değerini döndür
// topla(3, 7) sonucunu yazdırSample solution
function topla(a: number, b: number) {
return a + b;
}
console.log(topla(3, 7));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>function selam(isim: string)</code> guarantee?
- The isim parameter is optional
- The function returns a string
- The function is constant
- Only string values can be passed as isim Correct answer
Explanation: <code>isim: string</code> means the parameter accepts only strings; passing a number or boolean causes a compile error.
2 Add the parameter type
function kare(kenar: ____) { return kenar * kenar; }
function kare(kenar: number) { return kenar * kenar; }
Explanation: The multiplication <code>kenar * kenar</code> is performed, so the parameter must be <code>number</code>. <code>string</code> and <code>boolean</code> cannot be multiplied, and <code>void</code> is not a parameter type.
3 Parameter annotation concepts
| Term | Meaning |
|---|---|
function f(a: number) |
Parameter type declaration |
isim: string |
String parameter |
yas: number |
Number parameter |
Parametre annotation |
Giving a type to each parameter |