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

TypeScript:泛型类中如何让typeof方法返回基础类型而非字面量类型

解决方案

要解决这个问题,我们需要通过条件类型将泛型T的字面量类型映射到对应的基础类型字符串('string'或'number'),而不是直接使用字面量本身。

步骤1:定义基础类型映射的条件类型

先声明一个条件类型,用来判断泛型T的基础类型,并返回对应的字符串字面量:

type BaseType<T extends string | number> = T extends string ? 'string' : 'number';

这个类型会检查:如果T是string的子类型(包括所有字符串字面量),就返回'string';如果是number的子类型(包括数字字面量),就返回'number'。

步骤2:修改类的方法返回类型

将typeOfValue方法的返回类型替换为上面定义的BaseType<T>,同时调整类型断言:

type BaseType<T extends string | number> = T extends string ? 'string' : 'number';

class MyClass<T extends string | number> {
    public constructor(private value: T) {}
    
    public typeOfValue(): BaseType<T> {
        return typeof this.value as BaseType<T>;
    }
}

验证效果

现在实例化类时,返回的类型会符合预期:

const foo = new MyClass('foo');
const theType = foo.typeOfValue(); // 类型为'string'(不再是'foo')

const numInstance = new MyClass(456);
const numType = numInstance.typeOfValue(); // 类型为'number'

原问题分析

原代码中使用${T}作为返回类型,会把泛型T的字面量类型直接转换为字符串字面量(比如T是'foo'时,${T}就是'foo'),但JavaScript的typeof操作符实际返回的是"string"或"number",导致类型定义和实际值不匹配。通过条件类型BaseType<T>,我们可以准确映射到typeof操作符的真实返回类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:21:36