Best common type
- TypeScript course
- Beginner
- Lesson 36/89
- 4 min
Learn the best common type in arrays.
Best common type
When you declare an array, TypeScript finds the common type of the elements. If all elements share a type, that type is used. For example, [1, 2, 3] is inferred as number[].
let sayilar = [1, 2, 3]; // number[]
let metinler = ["a", "b"]; // string[]The common type is the narrowest type that covers all elements of the array.
Union type in arrays
If array elements have different types, TypeScript infers a union type. For example, ["a", 1] is inferred as (string | number)[]. This means each element can be either a string or a number.
let karisik = ["a", 1];
// type: (string | number)[]A union type combines different types with the | operator.
Practice Declare arrays and print first elements
Declare an array named sayilar with value [10, 20, 30]. Declare an array named karisik with value ["metin", 42]. Print the first element of sayilar first, then the first element of karisik, both with console.log.
Starter code
// sayilar adında bir dizi tanımla, üç sayı içersin
// karisik adında bir dizi tanımla, dize ve sayı içersin
// sayilar'ın ilk öğesini yazdır
// karisik'ın ilk öğesini yazdırSample solution
let sayilar = [10, 20, 30];
let karisik = ["metin", 42];
console.log(sayilar[0]);
console.log(karisik[0]);Expected output
10 metin
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In <code>let dizi = [1, 2, 3];</code>, what is the inferred type of <code>dizi</code>?
- number[] Correct answer
- any[]
- [number, number, number]
- (string | number)[]
Explanation: Since all elements are numbers, the best common type is <code>number</code>; the array type is inferred as <code>number[]</code>.
2 Complete the union type
let dizi: (string | ____)[] = ["a", 1];
let dizi: (string | number)[] = ["a", 1];
Explanation: Since the array contains both a string and a number, the union type must be <code>string | number</code>; <code>boolean</code>, <code>void</code> and <code>never</code> are types not present in the array.
3 Best common type concepts
| Term | Meaning |
|---|---|
[1, 2, 3] |
Infers number[] |
["a", 1] |
Infers (string | number)[] |
string | number |
Union type |
Best common type |
Finding the common type in an array |