以下是代码:

exp或t 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> => {

下面是它的调用方式:

const content = await quickPrompt({
  name: 'writeArticleSection',
  onUpdate,
  prompt,
});

const content = await quickPrompt({
  name: 'writeArticleSection',
  onUpdate,
  prompt,
  zodSchema: z.array(z.string())
});

在第一种情况下,我预计content将具有类型string(因为T extends 未定义) and in the second I expect it to be 字符串[](becauseTdoes not extend未定义`)

I've tried using T extends never and such, but I cannot get it to w或k as expected.

推荐答案

在第一种情况下,我希望内容的类型为string(因为T扩展了undefined)

这是不对的.

不受约束的泛型隐式约束为unknown,而不是undefined.如果将鼠标悬停在不带模式的quickPrompt调用上,它应该显示泛型参数的类型为:

const quickPrompt: <unknown>({ name, ...
//                  ^ here

相反,您可以将Tdefault类型指定为undefined,现在如果无法推断任何内容,则将使用该类型.

const quickPrompt: <T = undefined>({ ... }) => { /*...*/ }

See Playground


不过,通常情况下,为条件类型赋值将很难实现.函数重载可能会为您提供更好的服务:

// No schema
function quickPrompt(options: {
  name: string;
  onUpdate: () => Promise<{ cancelled: boolean }>;
  prompt: string;
  zodSchema?: undefined;
}): Promise<string>

// with schema
function quickPrompt<T>(options: {
  name: string;
  onUpdate: () => Promise<{ cancelled: boolean }>;
  prompt: string;
  zodSchema: z.ZodType<T>;
}): Promise<T>

// implementation
function quickPrompt(options: {
  name: string;
  onUpdate: () => Promise<{ cancelled: boolean }>;
  prompt: string;
  zodSchema?: z.ZodType<unknown>;
}): Promise<unknown> {
  return {} as any // TODO: implement
}

See playground

Typescript相关问答推荐

React-Native运行方法通过监听另一个状态来更新一个状态

为什么缩小封闭内部不适用于属性对象,但适用于声明的变量?

Angular中的其他服务仅获取默认值

TypeScript Page Routing在单击时不呈现子页面(React Router v6)

更新为Angular 17后的可选链运算符&?&问题

无法绑定ngModel.条件ngSwitchCase中的错误

参数属性类型定义的REACT-RUTER-DOM中的加载器属性错误

有没有可能为这样的函数写一个类型?

路由链接始终返回到

使用数组作为类型中允许的键的列表

如何在ANGLE中注册自定义验证器

基元类型按引用传递的解决方法

对象类型的TypeScrip隐式索引签名

如何将对象数组中的键映射到另一种对象类型的键?

在TypeScript中扩展重载方法时出现问题

如何从一个泛型类型推断多个类型

如何在本地存储中声明该类型?

如何实现允许扩展泛型函数参数的类型

在对象数组中设置值

断言同级为true或抛出错误的Typescript函数