I am looking to create a function that can generically return a partial object of a specific type, where the object has an ID property. When working with a concrete type, such as the example below, the function works smoothly:
type Person = {
id: string;
name: string;
}
const generatePartialPerson = (): Partial<Person> => {
const id = crypto.randomUUID() as string;
const obj: Partial<Person> = { id };
return obj;
}
However, when attempting to make the function generic so that it can handle any type with an {id: string} property, I encountered a type error:
Type '{ id: string; }' is not assignable to type 'Partial<T>'
const generatePartialGeneric = <T extends { id: string }>(
): Partial<T> => {
const id = crypto.randomUUID() as string;
const obj: Partial<T> = { id };
return obj;
};
My assumption is that the error occurs because a type that extends {id: string}
could potentially further constrain the ID property, like setting it to a fixed string literal as shown below:
interface FixedPerson extends Person {
id: "81a245c8-691e-471b-b07f-35e3ea3257ae";
}
Is there a way to define a generic constraint that ensures the type/subtype must have an {id: string}
property without any further constraints?