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

如何为方括号中的类型参数指定类型?为何该写法会报错?

报错原因及解决方案

报错原因

Foo['myFunc']<string>的写法属于TypeScript语法错误,因为类型解析器无法区分这里的<是泛型参数的起始符号还是比较运算符,会将其当作小于号处理,进而抛出“Parsing error: ';' expected”的解析错误。TypeScript不支持直接对通过索引访问得到的泛型函数类型使用尖括号传递泛型参数。

优雅的正确实现方式

方式一:利用类的原型(适用于Foo是类的场景)

如果Foo是类,可以直接通过原型访问泛型函数并指定类型参数,无需声明临时变量:

type stringFunc = typeof Foo.prototype.myFunc<string>;

方式二:通用工具类型封装

如果Foo是接口或其他类型,可封装工具类型来绑定泛型参数,适配更复杂场景:

// 替换类型中的目标泛型参数
type ReplaceGeneric<Type, From, To> = 
  Type extends From 
    ? To 
    : Type extends object 
      ? { [K in keyof Type]: ReplaceGeneric<Type[K], From, To> } 
      : Type;

// 给泛型函数绑定指定的类型参数
type BindGenericFunc<Func extends <T>(...args: any[]) => any, T> = 
  Func extends <U>(...args: infer Args) => infer Return 
    ? (...args: ReplaceGeneric<Args, U, T>) => ReplaceGeneric<Return, U, T> 
    : never;

// 使用示例
type stringFunc = BindGenericFunc<Foo['myFunc'], string>;

方式三:简化版类型推导(已知函数签名时)

如果清楚myFunc的具体签名,比如<T>(arg: T) => T,可以直接写出绑定类型后的函数类型:

type stringFunc = (arg: string) => string;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 06:25:04