I am currently working on developing a function with specific parameters. The first parameter, 'data', should be an array consisting of objects of type Product. The second parameter, 'element', can be any property within Product. Additionally, the third and fourth parameters specify properties of the 'element' we are targeting.
For example, if the 'Product' object includes a property named 'Customer', my goal is to extract the 'Id' and 'Name' attributes from the Customer section.
Below is the code snippet I have been using:
function getFilterItem<T extends keyof Product, K extends Product[T]>(
data: Product[],
element: T,
id: K extends Product[T] ? keyof K : never,
name: K extends Product[T] ? keyof K : never,
): FilterItem[] {
// functionality removed for simplicity
}
The desired way to call this function would look like:
getFilterItem(data, 'customer', 'id', 'name');
While the current implementation correctly identifies parameters, there is an issue when attempting to access the specified property. An error arises stating "Type 'K extends Product[T] ? keyof K : never' cannot be used to index type".
This error might occur due to the fact that Product[T] can be of any type within Product. For instance, if the 'Product' object contains a numerical property like 'price', trying to call
getFilterItem(data, 'price', 'id', 'name);
would lead TypeScript to struggle with indexing using the third and fourth parameters.
Given the full code block provided below (with certain logic omitted), how can we enable 'id' as a key of 'Product[T]'?
For reference, I've included a functional example where we aim to obtain 'id' and 'autonomyLevel' from a nested property within Product: