I have been struggling to extract a list of available IDs from an object array. Despite my attempts at trial and error, I am hopeful that someone can offer me some assistance.
Here is an example of the array structure:
const myValues = [
{id: 'abc', label: 'anyLabelForAbc'},
{id: 'xyz', label: 'anyLabelForXyz'},
{id: 'foo', label: 'anyLabelForFoo'},
{id: 'bar', label: 'anyLabelForBar'},
]
My goal is to retrieve all available IDs such as 'abc' | 'xyz' | 'foo' | 'bar' from a generic type like this:
const availableIds: AvailableIds<typeof myValues > = 'abc' //'abc' | 'xyz' | 'foo' | 'bar'
Despite trying various methods, none of my attempts seem to be working correctly. The current code I have doesn't yield the desired results:
type Item = { id: string; label: string };
type Index<T> = T extends number ? T : never;
type Ids<T extends Item []> = T[Index<T>]['id'];
const items: Item[] = {
{id: 'abc', label: 'anyLabelForAbc'},
{id: 'xyz', label: 'anyLabelForXyz'},
{id: 'foo', label: 'anyLabelForFoo'},
{id: 'bar', label: 'anyLabelForBar'},
}
const ids: Ids<typeof items> = ''; // not receiving any suggested output
Any help would be greatly appreciated. Thank you.