Generic functions
- TypeScript course
- Intermediate
- Lesson 16/89
- 4 min
Learn to define generic functions.
Generic function definition
A generic function takes a type parameter in <T> right after its name. This parameter can be used anywhere in the signature: parameter type, return type, or body. The type parameter makes the function reusable for every type.
function sarma<T>(x: T): T[] {
return [x];
}
const n = sarma(5); // number[]
const m = sarma("merhaba"); // string[]Explicit vs inferred type
Writing the type parameter explicitly is optional; TypeScript infers it from the argument. For readability or when inference is ambiguous, you can still give an explicit type argument like sarma<number>(5). Both forms produce the same result.
Practice Combine two values
Write a generic function birlestir<T> with two parameters a: T and b: T, and return type T[]. It should return the two values as an array. Then print the result of birlestir(3, 5) with console.log.
Starter code
// birlestir<T>(a: T, b: T): T[] fonksiyonunu yaz
// [a, b] dizisini döndür
// birlestir(3, 5) sonucunu console.log ile yazdırSample solution
function birlestir<T>(a: T, b: T): T[] {
return [a, b];
}
console.log(birlestir(3, 5));Expected output
[ 3, 5 ]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The call below does not give an explicit type argument. What happens?
function sarma<T>(x: T): T[] { return [x]; }
const n = sarma(5);- Gives a compile error
- T becomes any
- T becomes string
- TypeScript infers T as number Correct answer
Explanation: TypeScript infers T from the argument 5 being a number. So writing an explicit type argument is not required.
2 Explicit type argument
function kimlik<T>(x: T): T { return x; }
const n = kimlik<____>(42);
function kimlik<T>(x: T): T { return x; }
const n = kimlik<number>(42);
Explanation: Since 42 is a number, the type argument must be number. string or boolean cause a compile error; T is undefined at the call site.
3 Generic function parts
| Term | Meaning |
|---|---|
function ad<T> |
Generic function header |
<T> |
Type parameter declaration |
kimlik<number>(42) |
Explicit type argument |
kimlik(42) |
Inferred type argument |