You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

函数调用时规避重复泛型类型:为何第二个调用无法自动推断泛型?

TypeScript泛型推断失败原因解析

代码示例

type ModelType = { [key: string]: unknown };
type IsNullStr<T extends ModelType> = `isNull("${string & keyof T}")`;

declare class Query {
  static isNull: <T extends ModelType>(attribute: string & keyof T) => IsNullStr<T>;
}

type TodoList = { id: string; };

declare function listDocuments<T extends ModelType>(queries: IsNullStr<T>): void;

// 正常通过类型校验
listDocuments<TodoList>(Query.isNull<TodoList>("id"));
// 类型校验失败,无法自动推断Query.isNull的泛型为TodoList
listDocuments<TodoList>(Query.isNull("id"));

问题原因

TypeScript的泛型推断逻辑是从函数的输入参数推导泛型参数,而非从函数调用的上下文(比如传入的目标函数的参数类型要求)反向推导。

这里Query.isNull是一个独立的泛型函数,它的泛型T仅由自身的参数attribute推导。当你调用Query.isNull("id")时,TypeScript只能推断出T是包含id属性的任意类型(比如{ id: unknown }),但无法关联到listDocuments显式指定的TodoList——因为这两个函数的泛型参数是完全独立的,TypeScript不会主动将listDocuments的泛型约束反向应用到Query.isNull上。

最终Query.isNull("id")返回的类型是基于推断出的泛型(而非TodoList)生成的IsNullStr<T>,和listDocuments<TodoList>要求的IsNullStr<TodoList>类型不匹配,因此触发类型校验失败。

内容的提问来源于stack exchange,提问作者Nevus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 13:50:27