I'm currently diving into the world of TypeScript, teaching myself by putting my newfound knowledge into practice.
Below is the code I'm working on, but I've hit a roadblock trying to access the fields of the type passed to the function.
Code :
interface Product1 {
name: string;
category: string;
}
interface Product2 {
name: string;
price: number;
}
type Product = Product1 | Product2;
function DisplayProductDetails(data: Product) {
const keys : string[] = Object.keys(data);
keys.forEach((key) => {
console.log(data[key])
})
}
const p2 = {
name: "iPhone",
price: 999
}
DisplayProductDetails(p2)
Error: The error is on this line - console.log(data[key])
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Product'. No index signature with a parameter of type 'string' was found on type 'Product'.