I've been researching various resources to find a solution for the error I'm encountering, but haven't found one that fits my specific case.
My goal is to populate dummy rows in my web application so that I can use them as placeholders for the loading state when using MUI Skeleton.
I am aiming to create a function that takes an object with certain properties of a specified type and returns an array with IDs included.
export const generateDummyRows = <T extends { id: string }>(
count: number,
record: Omit<T, "id">,
): T[] => Array.from({ length: count }, (_, i) => ({ ...record, id: `${i}` }));
The Array.from
expression triggers this type error message:
Type '(Omit<T, "id"> & { id: string; })[]' is not assignable to type 'T[]'.
Type 'Omit<T, "id"> & { id: string; }' is not a valid assignment for type 'T'.
While 'Omit<T, "id"> &a`mT;<string> }' can be assigned to the constraints of type 'T', there might exist another subtype of constraint '{ id: string; }' that could be selected instead. (2322)
Do you have any suggestions on how to rectify this issue?
Here's an example of how to use the function:
const dummyRows = generateDummyRows<Student>(10, {
firstName: string,
lastName: string,
createdAt: Date.now(),
});
UPDATE regarding @jcalz's comment: Initially, I had marked record
as optional because I have a record type where all properties are optional except for id
. This setup would allow for a call like generateDummyRows<Foo>(3)
which would result in
[{id: '0'}, {id: '1'}, {id: '2'}]
.
I am open to alternative suggestions, such as avoiding the use of Omit
, but I prefer not to resort to type assertion (as
) since it seems to override the issue, as mentioned in @Alexis' response below. Is this correct?