I have the following schema columns for a database table (used for Watermelon DB).
const columns = [ { name: "created_at", type: "number", isOptional: true }, { name: "created_by", type: "string" }, { name: "is_corrupt", type: "boolean", isOptional: true }, ];
I would like to create a generic which will create the following type from the above example, how can I do that?
type ExpectedInferredTypeFromColumns = { created_at: number | null; created_by: string; is_corrupt: boolean | null; };
My attempt:
type InferTypeFromColumns<T extends ReadonlyArray<Column>> = { [K in T extends ReadonlyArray<infer U> ? U extends { name: string } ? U["name"] : never : never]: T extends ReadonlyArray<infer U> ? U extends { type: "number"; isOptional: true } ? number | null : U extends { type: "number" } ? number : U extends { type: "string"; isOptional: true } ? string | null : U extends { type: "string" } ? string : U extends { type: "boolean"; isOptional: true } ? boolean | null : U extends { type: "boolean" } ? boolean : never : never; }; type MyInferredType = InferTypeFromColumns<typeof columns>; // Produces: => // type MyInferredType = { // created_at: string | number | boolean | null; // created_by: string | number | boolean | null; // is_corrupt: string | number | boolean | null; // }
As you can see my attempt doesn't quite meet my ExpectedInferredTypeFromColumns