Skip to content

Commit f9b1496

Browse files
committed
practice question 3 solved
1 parent ad204f5 commit f9b1496

File tree

1 file changed

+18
-6
lines changed
  • src/module-4.5-practice

1 file changed

+18
-6
lines changed

src/module-4.5-practice/3.ts

+18-6
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,25 @@ const productArr: IProduct[] = [
2525
{ id: 8, name: "movie", price: 0, category: "entertainment" },
2626
];
2727

28-
const filterProduct = <T, U>(productArr: T, value: U) => {
29-
const newArr = (productArr as IProduct[]).filter(
30-
(product) => product.category === value
31-
);
28+
const filterProduct = <T extends IProduct>(
29+
productArr: T[],
30+
criterion: keyof T,
31+
value: T[keyof T]
32+
) => {
33+
const newArr = productArr.filter((product) => product[criterion] === value);
3234
console.log(newArr);
3335
return newArr;
3436
};
3537

36-
filterProduct<IProduct[], string>(productArr, "study");
37-
// How can I make the property dynamic? like I can send id, name, price etc dynamically.
38+
filterProduct(productArr, "category", "entertainment");
39+
40+
/**
41+
* T extends IProduct
42+
* T === { id: number; name: string; price: number; category: string;}
43+
*
44+
* T[keyof T]
45+
* When T = { id: 6, name: "comic", price: 0, category: "entertainment" }
46+
* keyof T = "id" | "name" | "comic" | "price" | "category"
47+
* for category, T [keyof T] = T ["category"]
48+
* for id, T [keyof T] = T ["id"]
49+
*/

0 commit comments

Comments
 (0)