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

TypeScript:计算式泛型类型无法正常工作

问题分析与解决方案

问题根源

你定义的ValidationFunction返回的是一个泛型函数(Val是函数自身的泛型参数),而非基于外层T和IsMandatory确定的具体函数类型。这导致两个核心问题:

  • 即使指定ValidationFunction<string, true>,test仍然是泛型函数,参数Val可被推断为任意类型,因此test能接受任何参数;
  • 赋值时返回val报错,因为Val是泛型类型,TypeScript无法确认它属于函数返回值要求的true | string类型集合。

修正后的类型定义

调整类型逻辑,直接根据T和IsMandatory生成具体的函数类型,避免返回泛型函数:

// Mandatory = true 表示参数必填
export type ValidationFunction<T = unknown, IsMandatory extends boolean = boolean> =
  IsMandatory extends true 
    ? (val: T) => true | string 
    : (val: T | undefined) => true | string;

验证修正效果

使用修正后的类型定义,代码行为完全符合预期:

const test: ValidationFunction<string, true> = (val) => {
  return val; // 无错误,val被正确推断为string类型,符合返回值要求
};

test('poop'); // 正常通过类型检查
test(555);    // 报错:类型"number"不能赋值给类型"string"
test(true);   // 报错:类型"boolean"不能赋值给类型"string"
test(null);   // 报错:类型"null"不能赋值给类型"string"
test({});     // 报错:类型"{}"不能赋值给类型"string"

关键说明

  • 新增IsMandatory extends boolean约束,确保第二个泛型参数只能是布尔值;
  • 通过条件类型直接生成对应参数类型的函数,而非返回泛型函数,彻底固定参数类型范围,杜绝任意类型输入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:46:00