Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a type from a const object

I have a Field type:

type Field = { name: string; type: 'string' | 'number' };

And a list of Fields.

const fields = [
    { name: 'field1', type: 'string' },
    { name: 'field2', type: 'string' },
    { name: 'field3', type: 'number' }
] as const satisfies readonly Field[];

Is it possible to infer fields into a type that looks like the below type?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type MyObject = {
    field1: string;
    field2: string;
    field3: number;
}

The closest I could get to is:

type MyObject = Record<typeof fields[number]["name"], typeof fields[number]["type"]>;

which yields:

{field1: "string" | "number", field2: "string" | "number", field3: "string" | "number"}

Close, but not exactly what I want.

>Solution :

type Field = { name: string; type: 'string' | 'number' };
const fields = [
    { name: 'field1', type: 'string' },
    { name: 'field2', type: 'string' },
    { name: 'field3', type: 'number' }
] as const satisfies readonly Field[];

type NameMap = {
    string: string;
    number: number;
}
type X<T extends readonly Field[]> = { [K in T[number]['name']]: NameMap[Extract<T[number], { name: K }>['type']] }
type MyObject = X<typeof fields>
//   ^?
// type MyObject = {
//     field1: string;
//     field2: string;
//     field3: number;
// }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading