Let's tackle the challenge of constructing a new type in Typescript based on an descriptive object named schema
, which contains all the requirements expressed within it.
Here is my proposed solution:
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>;
Consider the sample schema below:
const schema = [
{ name: "firstName", type: { kind: "STRING" } },
{ name: "age", type: { kind: "NUMBER" } },
{ name: "acceptedTerms", type: { kind: "BOOLEAN", optional: true } }
] as const;
We can then extract the inferred type using the following code snippet:
export const schemaExtracted = extractType(schema);
However, the extracted result may not be entirely correct:
// 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
// };
Utilizing typeof
to obtain a static type leads to the same error:
type SchemaTyped = typeof schemaExtracted;
// type SchemaTyped = {
// firstName: "STRING";
// age: "NUMBER";
// acceptedTerms: "BOOLEAN";
// };
In trying to create a demo object using the generated type, we encounter another TypeScript error due to the mismatch in types:
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 would be the most effective approach to rectify this issue or implement a refined solution?
Your assistance is greatly appreciated!