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

是否存在可在表达式中使用typeof的TypeScript hack方案?

TypeScript中对泛型函数表达式使用typeof的hack实现

TypeScript官方设计上不支持对表达式直接使用typeof操作符,但可以通过条件类型推断的hack方式实现你需要的效果,无需额外声明中间常量。

实现代码

function a_function<T>() {
    return {} as any
}

// 类型工具:提取函数的返回类型
type GetReturnType<Fn extends (...args: any[]) => any> = 
    Fn extends (...args: any[]) => infer R ? R : never;

// 直接获取泛型函数调用表达式的类型
type WithoutConst<T> = GetReturnType<typeof a_function<T>>;

// 验证一致性
const a_value = a_function<true>();
type UsingConst = typeof a_value; // any
type TestMatch = WithoutConst<true>; // any,结果一致

原理说明

通过定义GetReturnType类型工具,利用TypeScript的infer关键字推断泛型函数实例化后的返回类型,绕过了typeof不能直接作用于表达式的限制。该方法同样适用于带参数的泛型函数:

function demoFn<T>(input: T) {
    return { data: input } as { result: T };
}

type DemoReturnType<T> = GetReturnType<typeof demoFn<T>>;
type StringResult = DemoReturnType<string>; // { result: string }

适配测试需求

这种方式可以直接用于类型开发的快速测试,无需每次声明临时常量,直接通过类型工具获取目标表达式的类型,符合标准化测试的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 21:42:32