为何T extends undefined条件在属性上下文场景下不生效?
TypeScript泛型条件类型适配方案
问题场景
定义的quickPrompt函数期望根据是否传入zodSchema参数返回不同类型:
- 不传入
zodSchema时,返回string类型 - 传入
zodSchema(如z.array(z.string()))时,返回对应解析后的类型(如string[])
但当前泛型写法未达到预期效果。
原问题代码
函数定义:
export const quickPrompt = async <T>({ name, prompt, zodSchema, onUpdate, }: { name: string; onUpdate: () => Promise<{ cancelled: boolean }>; prompt: string; zodSchema?: z.ZodType<T>; }): Promise<T extends undefined ? string : T> => {
调用示例:
// 期望content类型为string const content = await quickPrompt({ name: 'writeArticleSection', onUpdate, prompt, }); // 期望content类型为string[] const content = await quickPrompt({ name: 'writeArticleSection', onUpdate, prompt, zodSchema: z.array(z.string()) });
修正方案
方案1:给泛型设置默认值
通过给泛型T设置默认值undefined,确保不传入zodSchema时触发string返回分支:
import { z } from 'zod'; export const quickPrompt = async <T = undefined>({ name, prompt, zodSchema, onUpdate, }: { name: string; onUpdate: () => Promise<{ cancelled: boolean }>; prompt: string; zodSchema?: z.ZodType<T>; }): Promise<T extends undefined ? string : T> => { // 函数实现逻辑示例 const rawResult = await fetchPromptResult(prompt); // 假设的异步获取结果逻辑 if (zodSchema) { return zodSchema.parse(rawResult) as T; } return rawResult as string; };
方案2:基于Zod Schema直接推断类型
通过泛型捕获zodSchema的类型,使用z.infer直接获取解析后类型,逻辑更清晰:
import { z } from 'zod'; export const quickPrompt = async <Schema extends z.ZodType | undefined = undefined>({ name, prompt, zodSchema, onUpdate, }: { name: string; onUpdate: () => Promise<{ cancelled: boolean }>; prompt: string; zodSchema?: Schema; }): Promise<Schema extends z.ZodType ? z.infer<Schema> : string> => { const rawResult = await fetchPromptResult(prompt); if (zodSchema) { return zodSchema.parse(rawResult) as z.infer<Schema>; } return rawResult as string; };
效果验证
- 不传入
zodSchema时,返回值类型自动推断为string - 传入
z.array(z.string())时,返回值类型自动推断为string[]
内容的提问来源于stack exchange,提问作者Ada Boese
相关产品推荐
相关产品推荐

