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?
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;
// }