I have an array of objects:
const input = [
{ id: "a" },
{ id: 5 }
]
I would like to create function, that will return id property from one of those objects in the array and I need to have it exact type from the input.
interface Data<Id> {
id: Id
}
const getFirstId = <Id>(data: ReadonlyArray<Data<Id>>): Id => {
return data[0].id
}
const firstId = getFirstId(input) // firstId should be "a" | 5.
My attempt above however works only if all ids are strings (eg. "a" | "b") or only numbers (eg. 1 | 2), but if I combine more types together, the function doesn't want to accept input argument with an error:
Type 'number' is not assignable to type '"a"'.
How can I fix it? Here is an example.