

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Generics
incomplete
2: Multiple Type Parameters
incomplete
3: Generic Constraints
incomplete
4: Type Parameters for Types
incomplete
5: Generic Type Inference
incomplete
6: Generic Classes
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Type parameters aren't just limited to functions and methods! You can use type parameters to create generic types as well! For example:
interface Store<T> {
get(id: string): T;
save(id: string, item: T): void;
list(): T[];
}
// also works with type aliases using
// type Store<T> = { ... }
Now a Store can be anything that implements the methods above, but what is stored doesn't matter. Next we can create a function that uses the store, again, not caring about what is stored inside of it:
function addAndGetItems<T>(store: Store<T>, id: string, newItem: T): T[] {
store.save(id, newItem);
return store.list();
}
Finally, we can create a Store that specifically deals with Product types:
type Product = {
name: string;
price: number;
};
const productStore = {
products: {} as Record<string, Product>,
get(id: string): Product {
return this.products[id];
},
save(id: string, item: Product): void {
this.products[id] = item;
},
list(): Product[] {
return Object.values(this.products);
},
};
And we can use it like this:
const newStore = addAndGetItems(productStore, "laneslaptop", {
name: "Laptop",
price: 999,
});
console.log(newStore);
// [{ "name": "Laptop", "price": 999 }]
const finalStore = addAndGetItems(productStore, "allanstoaster", {
name: "Toaster",
price: 50,
});
console.log(finalStore);
// [{ "name": "Laptop", "price": 999 }, { name: 'Toaster', price: 50 }]
We could also create a store for something entirely different!
type Homunculus = {
title: string;
abilities: string[];
};
const homunculusStore = {
homunculi: {} as Record<string, Homunculus>,
get(id: string): Homunculus {
return this.homunculi[id];
},
save(id: string, item: Homunculus): void {
this.homunculi[id] = item;
},
list(): Homunculus[] {
return Object.values(this.homunculi);
},
};
and it will still work with addAndGetItems:
const newHomunculus = addAndGetItems(homunculusStore, "laneslaptop", {
title: "Laptop",
abilities: ["fast", "strong"],
});
console.log(newHomunculus);
// [{ "title": "Laptop", "abilities": ["fast", "strong"] }]
The infra team at Support.ai is building a shared job queue for internal systems – model retraining, cache invalidation, moderation sync, and more.
Take a look at the createQueue function that's been created for you. It creates a new generic JobQueue data structure.
Array.prototype.shift() removes and returns the first element of the array, or undefined if it's empty.