#How to infer types from an array in a generic object

22 messages · Page 1 of 1 (latest)

hollow field
#

`const config = {
animals: {
type: "select",
options: ["cat", "dog"] as const,
},
};

type FormData<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends { type: "select"; options: readonly any[] }
? T[K]["options"][number]
: never;
};

type Result = FormData<typeof config>;
// Result is:
// {
// animals: "cat" | "dog";
// }`

#

HI bro

turbid linden
#

Awesome I’ll try it out thank you. Still learning TS ^.^

#

I'm still getting 'never, strange

hollow field
#

soryy, let me check again

turbid linden
#

yes, i copied from your example verbatim. weird

hollow field
# turbid linden yes, i copied from your example verbatim. weird

check again bro
`const config = {
animals: {
type: "select",
options: ["cat", "dog"] as const,
},
};

type FormData<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends { type: "select"; options: infer O extends readonly any[] }
? O[number]
: never;
};

type Result = FormData<typeof config>;
// ✅ Result = { animals: "cat" | "dog" }`

turbid linden
hollow field
turbid linden
#

it still comes back as never

#

one sec, i'll check my ts version

#

Version 5.8.3

fathom breachBOT
#
retsam19#0

Preview:```ts
const config = {
animals: {
type: "select",
options: ["cat", "dog"] as const,
},
}

type MyFormData<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends {
type: "select"
options: infer O extends readonly any[]
}
? O[number]
: neve
...```

hollow field
#

`const config = {
animals: {
type: "select",
options: ["cat", "dog"] as const,
},
};

type FormData<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends { type: "select"; options: infer O extends readonly any[] }
? O[number]
: never;
};

type Result = FormData<typeof config>;
// Result = { animals: "cat" | "dog" }`

somber jasper
#

@hollow field ^ Here's a typescript playground - it's also coming back as never here; maybe you can show a version that works here. (I had to rename FormData because there's a DOM built-in type that it conflicts with)

#

Rather than repeatedly sending the same codeblock, you can make it work in the playground and post the link here.

turbid linden
#

I appreciate the help

#

I got it to work!!

#

you need to make the whole config as const

fathom breachBOT
#
meecat#0

Preview:```ts
const config = {
animals: {
type: "select",
options: ["cat", "dog"],
},
} as const

type MyFormData<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends {
type: "select"
options: infer O extends readonly any[]
}
? O[number]
: neve
...```

turbid linden
#

thank you so mcuh