i try to get a list of available id's from a object array. After search, trail and error i hope i can find some help.
I have a array which contains a objects, like this example:
const myValues = [
{id: 'abc', label: 'anyLabelForAbc'},
{id: 'xyz', label: 'anyLabelForXyz'},
{id: 'foo', label: 'anyLabelForFoo'},
{id: 'bar', label: 'anyLabelForBar'},
]
In the next step i would get all available id's like 'abc' | 'xyz' | 'foo' | 'bar' from a generic type like
const availableIds: AvailableIds<typeof myValues > = 'abc' //'abc' | 'xyz' | 'foo' | 'bar'
I have try different ways, but none of my attempts works as expected. This is my code now which doesnt works
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> = ''; // geting nothing suggested
Thank you