TypeScript
Challenge 4: Mini app
Solve a task testing the full intermediate level.
Mini app challenge
This challenge tests the entire intermediate level. You will combine interfaces for data models, generic functions, access modifiers, and display functions to build a working mini application. Each part carries its own responsibility and together they form a type-safe, working application.
Exercise Generic first element helper
Define a Urun interface: ad: string, fiyat: number. The ilk generic function should be <T>(arr: T[]): T | undefined and return arr[0]. The urunler array should contain two Urun objects: { ad: "kalem", fiyat: 5 } and { ad: "defter", fiyat: 10 }. Assign the result of ilk(urunler) to ilkUrun and print ilkUrun.ad.
Show example solution
interface Urun { ad: string; fiyat: number; }
function ilk<T>(arr: T[]): T | undefined {
return arr[0];
}
const urunler: Urun[] = [
{ ad: "kalem", fiyat: 5 },
{ ad: "defter", fiyat: 10 }
];
const ilkUrun = ilk(urunler);
console.log(ilkUrun.ad);
Exercise Task filtering app
Define a Gorev interface: ad: string, tamamlandi: boolean. The filtrele generic function should be <T>(arr: T[], kosul: (x: T) => boolean): T[]. Inside, declare an empty sonuc: T[] array, loop with for...of, if kosul(x) is true do sonuc.push(x), then return sonuc. The gorevler array should contain two Gorev objects: { ad: "a", tamamlandi: true } and { ad: "b", tamamlandi: false }. Assign the result of filtrele(gorevler, (g) => !g.tamamlandi) to aciklar and print aciklar.length.
Show example solution
interface Gorev { ad: string; tamamlandi: boolean; }
function filtrele<T>(arr: T[], kosul: (x: T) => boolean): T[] {
const sonuc: T[] = [];
for (const x of arr) {
if (kosul(x)) sonuc.push(x);
}
return sonuc;
}
const gorevler: Gorev[] = [
{ ad: "a", tamamlandi: true },
{ ad: "b", tamamlandi: false }
];
const aciklar = filtrele(gorevler, (g) => !g.tamamlandi);
console.log(aciklar.length);
Test yourself
-
What is the correct order of data model, generic function, and display steps in a mini app?
- Only generic, rest not needed
- Define model, write generic function, display
- Only display, model not needed
- First display, then model, then generic
Show answer
Define model, write generic function, display — Correct flow: first the data model is defined, then the generic function is written, and finally display is done.
-
Data model keyword
____ Gorev { ad: string; tamamlandi: boolean; }
Show answer
interface Gorev { ad: string; tamamlandi: boolean; }
-
Mini app parts
- interface
- Data model
- generic
- Type-safe helper
- extends
- Constraint
- console.log
- Output
Next lesson: Intermediate section exam