Is it possible to create a generic object type that would force the keys to be used as values internally?
For example, if I want an object to have the id that matches the key I would use something like the code below:
export type ObjectWithId<
T extends string,
E extends Record<string, unknown>
> = {
[K in T]: { id: K } & E;
};
type IdKeys = 'dog' | 'cat';
const animals: ObjectWithId<IdKeys, { title: string }> = {
dog: { id: 'dog', title: 'Some title' },
cat: { id: 'cat', title: 'Another title' },
};
But I wonder if there is a solution that could work without the need to declare the IdKeys and therefore would infer these values from the object.
e.g.
const animals: ObjectWithId<{ title: string }> = {
dog: { id: 'dog', title: 'Some title' },
cat: { id: 'cat', title: 'Another title' },
};
If I can't do it only with a type and need to use a Constrained Identity Function would then it still be possible to declare the type for the rest of the object?
e.g.
validateObjectWithId<{ title: string }>(
{ cat: { id: 'cat', title: 'Another title' } }
)
I would like to use validateObjectWithId() as a helper to validate only the id so it can be used with all sorts of data but still be able to declare the type for the rest of the data.