Default type parameter
- TypeScript course
- Intermediate
- Lesson 22/89
- 4 min
Learn to give a default value to a type parameter.
Default type parameter
You can give a type parameter a default with =: <T = string>. If you omit the type argument at the call, T becomes the default; if you give one, that type is used. This is handy for helpers that usually want one common type but occasionally want another.
function depola<T = string>(x: T): T[] {
return [x];
}
depola("metin"); // T = string
depola<number>(5); // T = numberDefault together with a bound
A default type can also be used together with a bound: <T extends Uzunluklu = string[]>. Here T must be at least Uzunluklu and defaults to string[]. The bound is a condition the default type must also satisfy; otherwise it is a compile error.
Practice Single-item array with a default type
Write the generic function sarma<T = string>(x: T): T[] with body return [x];. Print the result of sarma("merhaba") with console.log.
Starter code
// sarma fonksiyonunu generic olarak yaz
// T tür parametresine string varsayılan değer ver
// x parametresi T, dönüş T[] olsun
// gövde tek elemanlı dizi döndürsün
// "merhaba" metnini sar ve sonucu console.log ile yazdırSample solution
function sarma<T = string>(x: T): T[] {
return [x];
}
console.log(sarma("merhaba"));Expected output
[ 'merhaba' ]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In <code>depola<T = string>(x: T)</code>, what does the call <code>depola("merhaba")</code> do to T?
- Gives a compile error
- T becomes undefined
- T becomes any
- T becomes string (both default and inferred) Correct answer
Explanation: Since no type argument is given, the default string applies; and since "merhaba" is a string, inference also yields string. The two agree.
2 Give a default type
function ilk<T = ____>(dizi: T[]): T {
return dizi[0];
}
const s = ilk(); // T varsayılan
function ilk<T = string>(dizi: T[]): T {
return dizi[0];
}
const s = ilk(); // T varsayılan
Explanation: With no argument at the call, the default applies; the example expects a string array, so string is written. number or boolean break the call; T is undefined.
3 Default type parameter parts
| Term | Meaning |
|---|---|
<T = string> |
Default type declaration |
depola("metin") |
Default takes effect |
depola<number>(5) |
Given type overrides |
<T extends Uzunluklu = string[]> |
Bound and default together |