Experience a new aspect of Ids with my basic interface:
interface Identifiable {
id?: number;
}
Behold, a universal function that transforms record objects into entities with ids:
function transformRowToObject<T extends Identifiable>(row: { id: number; }): Partial<T> {
return { id: row.id };
// Type '{ id: number; }' is not assignable to type 'Partial<T>'.
}
The reason for this error lies within the extensibility of T
from Identifiable
. Certain types like { id: undefined }
or { id: 1 }
could make the return statement invalid. Hence, I made a modification to mandate a numerical id:
type Identified<T extends Identifiable> = {
[K in keyof T]?: K extends "id" ? number : T[K];
}
function adjustObjectType<T extends Identifiable>(row: { id: number; }): Identified<T> {
return { id: row.id };
// Type '{ id: number; }' is not assignable to type 'Identified<T>'.
}
But why does this occur? What combination of T
(where T extends Identifiable
) prevents { id: number }
from being assigned to Identified<T>
?
If there's no way to rectify the Identified
type for compatibility, is there an alternative method to define the conversion process for generic subtypes of Identifiable
?