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

如何获取函数返回值类型?TypeScript泛型类型推导需求问询

TypeScript中如何让函数返回值保留字面量类型并实现类型自动同步?

问题场景

你写了这样的代码:

const a = 'Hello' as const 
function f(){
    return a[0]
} 
const b = f()

结果变量b的类型被推断成了string,但你希望它保留'H'这个字面量类型。同时你需要实现类型层面的“函数映射”效果:

type A = 'Hello'
type B = f(A) // 希望B自动变成A的首字符类型,改A时B不用手动改

而且需求不止于字符串,数组、对象等场景也要适用,你知道泛型但不知道怎么用在这。

解决方法

一、值层面:让函数返回值保留字面量类型

核心是用泛型捕获输入的字面量类型,不让TypeScript自动把它拓宽成string、number这种宽泛类型。

字符串场景

const a = 'Hello' as const;
// 用泛型T捕获输入字符串的字面量类型
function f<T extends string>(str: T): T[0] {
    return str[0] as T[0];
}
const b = f(a); // b的类型现在是'H',完美保留字面量

数组场景

同样的思路套用到数组上:

const arr = [1, 2, 3] as const;
function getFirst<T extends readonly any[]>(arr: T): T[0] {
    return arr[0] as T[0];
}
const firstItem = getFirst(arr); // firstItem类型是1,不是number

对象场景

要获取对象属性的字面量类型,用双泛型分别捕获对象类型和属性名:

const obj = { name: 'Alice', age: 25 } as const;
function getProp<T extends object, K extends keyof T>(obj: T, key: K): T[K] {
    return obj[key];
}
const userName = getProp(obj, 'name'); // userName类型是'Alice'

二、类型层面:实现类型级别的自动映射

TypeScript支持写“类型工具”,相当于类型层面的函数,能实现修改输入类型时输出类型自动同步的效果。

字符串首字符的类型工具

用模板字符串类型和infer关键字提取首字符:

// 自定义类型工具:取字符串的第一个字符
type FirstChar<T extends string> = T extends `${infer C}${infer _}` ? C : never;

type A = 'Hello';
type B = FirstChar<A>; // B的类型是'H'
// 改A试试
type A2 = 'World';
type B2 = FirstChar<A2>; // B2自动变成'W'

数组首元素的类型工具

用数组解构的类型推断提取首元素:

type FirstItem<T extends readonly any[]> = T extends [infer C, ...infer _] ? C : never;

type ArrType = [1, 'foo', true];
type ArrFirst = FirstItem<ArrType>; // ArrFirst类型是1

对象属性的类型工具

直接用索引访问类型,或者封装成工具:

type GetProp<T extends object, K extends keyof T> = T[K];

type ObjType = { name: 'Bob', age: 30 };
type ObjName = GetProp<ObjType, 'name'>; // ObjName类型是'Bob'

核心逻辑

  • 值层面:用泛型“锁定”输入的字面量类型,让函数返回值的类型和输入强绑定,避免TypeScript自动拓宽类型。
  • 类型层面:利用TypeScript的类型推断、infer、模板字符串等特性,写自定义类型工具,实现类型之间的自动映射。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 17:17:39