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

TypeScript泛型实现:数组选择器到映射器的智能提示方法

问题背景

现有以下代码:

interface State {
    user: {
        name: string;
        age: number;
    }
}

const selection = (state: State) => [state.user.name, state.user.age] as const;
const state: State = { user: { name: "John Doe", age: 38 } };

需要实现一个泛型方法enricher,它接收状态对象、返回数组的选择器函数,并且让映射器函数自动获得对应属性的类型智能提示。

尝试编写了如下泛型代码,但在选择器与映射器的类型推导上遇到瓶颈:

const enricher = <T extends any[], U>(
  state: State,
  selectors: (state: State) => T,
  mapper: (...args: T) => U): U => {
  // 实现逻辑卡壳
}

const result = enricher(state, selection, (name, age) => `${firstName} - ${age}`);
console.log(result); // 期望输出 "John Doe - 38"

解决方案

你之前的泛型定义没有正确捕获选择器返回的只读元组类型(因为selection用了as const),导致映射器的参数类型无法被准确推导。调整泛型参数即可解决问题:

interface State {
    user: {
        name: string;
        age: number;
    }
}

const selection = (state: State) => [state.user.name, state.user.age] as const;
const state: State = { user: { name: "John Doe", age: 38 } };

// 泛型参数S接收状态类型,T接收选择器返回的只读元组类型
const enricher = <S, T extends readonly any[], U>(
  state: S,
  selector: (state: S) => T,
  mapper: (...args: T) => U
): U => {
  const selectedValues = selector(state);
  return mapper(...selectedValues);
};

// 此时映射器的name(string类型)、age(number类型)会自动获得智能提示
const result = enricher(state, selection, (name, age) => `${name} - ${age}`);
console.log(result); // 输出 "John Doe - 38"

关键说明

  1. 新增泛型参数S,让函数不局限于固定的State类型,通用性更强;
  2. 让T继承readonly any[],匹配as const生成的只读元组类型,确保TypeScript能精准捕获每个元素的具体类型;
  3. 实现逻辑:调用选择器获取值元组,用展开运算符将元组元素作为参数传给映射器,返回映射结果即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 15:22:42