Given an descriptive object called schema, construct a new type based on it that contains all the requirements expressed on this object with the correct Typescript typing.
My solution so far:
type ConfigParameter<IdType, ValueType> = Readonly<{
name: IdType;
type: { kind: ValueType };
}>;
type Config<T extends ReadonlyArray<ConfigParameter<string, any>>> = {
[K in T[number]["name"]]: Extract<T[number], { name: K }>["type"]["kind"];
} extends infer O
? { [P in keyof O]: O[P] }
: never;
export declare function extractType<O>(fields: O): Config<O>;
Given this sample schema:
const schema = [
{ name: "firstName", type: { kind: "STRING" } },
{ name: "age", type: { kind: "NUMBER" } },
{ name: "acceptedTerms", type: { kind: "BOOLEAN", optional: true } }
] as const;
It's possible to extract the inferred type:
export const schemaExtracted = extractType(schema);
But the returned result is as follows:
// const schemaExtracted: {
// firstName: "STRING"; WRONG, should be typed as string
// age: "NUMBER"; WRONG, should be typed as number
// acceptedTerms: "BOOLEAN"; WRONG, should be typed as optional BOOLEAN
// };
Then we can use typeof to have a static type, but the error follows:
type SchemaTyped = typeof schemaExtracted;
// type SchemaTyped = {
// firstName: "STRING";
// age: "NUMBER";
// acceptedTerms: "BOOLEAN";
// };
And at the end, when creating a demo object using the type generated we receive the TypeScript error, that is also wrong because of the wrong extracted type
const schemaDemo: SchemaTyped = {};
// const schemaDemo: {
// firstName: "STRING";
// age: "NUMBER";
// acceptedTerms: "BOOLEAN";
// }
// Type '{}' is missing the following properties from type '{ firstName: "STRING"; age: "NUMBER"; acceptedTerms: "BOOLEAN"; }': firstName, age, acceptedTerms
What's the best way of doing this or another approximated solution?
Thanks for the assistance!