How to extract tuple from array of objects for Zod enums?

export const PLANS = [
{
id: "0",
name: "free",
price: 0,
description: "Free Video Stream",
},
{
id: "price_1Nd",
name: "basic",
price: 5,
description: "Basic Video Stream",
},
{
id: "price_1Nd",
name: "standard",
price: 10,
description: "Standard Video Stream",
},
{
id: "price_1Nd",
name: "premium",
price: 20,
description: "Premium Video Stream",
},
] as const

const planNames = PLANS.map((plan) => plan.name)
// ("free" | "basic" | "standard" | "premium")[] what I get
// ["free", "basic", "standard", "premium"] what I want
export const PLANS = [
{
id: "0",
name: "free",
price: 0,
description: "Free Video Stream",
},
{
id: "price_1Nd",
name: "basic",
price: 5,
description: "Basic Video Stream",
},
{
id: "price_1Nd",
name: "standard",
price: 10,
description: "Standard Video Stream",
},
{
id: "price_1Nd",
name: "premium",
price: 20,
description: "Premium Video Stream",
},
] as const

const planNames = PLANS.map((plan) => plan.name)
// ("free" | "basic" | "standard" | "premium")[] what I get
// ["free", "basic", "standard", "premium"] what I want
I need this for zod validation. Currently, I'm doing this way.
z.object({
stripeProductId: z.string(),
planName: z.enum(["free", "basic", "standard", "premium"]),
}),
z.object({
stripeProductId: z.string(),
planName: z.enum(["free", "basic", "standard", "premium"]),
}),
2 Replies
Max
Max14mo ago
@Apestein type: z.nativeEnum(YourPrismaEnum),
Luc Ledo
Luc LedoOP14mo ago
Don't think you understood the question. Here is the answer I found though in case anyone else needs it.
const tupleMap = <
const T extends readonly Record<string, unknown>[],
Key extends keyof T[number],
>(
input: T,
key: Key,
): { [k in keyof T]: T[k][Key] } => {
return input.map((row) => row[key as never]) as never
}
export const planTuple = tupleMap(PLANS, "name") //type will be: const planTuple: readonly ["free", "basic", "standard", "premium"]
const tupleMap = <
const T extends readonly Record<string, unknown>[],
Key extends keyof T[number],
>(
input: T,
key: Key,
): { [k in keyof T]: T[k][Key] } => {
return input.map((row) => row[key as never]) as never
}
export const planTuple = tupleMap(PLANS, "name") //type will be: const planTuple: readonly ["free", "basic", "standard", "premium"]
Want results from more Discord servers?
Add your server