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

如何使TypeScript函数返回输入类型与数组指定属性的交叉类型?

可以实现这个需求

你只需要调整函数的泛型定义,利用TypeScript的类型推断和Record工具类型,就能让返回类型根据propsMapper传入的target字段动态扩展。

修改后的函数代码

export const buildLocalizedInfo = <T extends { id: number }, K extends string>(
    recordBuilder: (record: any) => T,
    propsMapper: readonly { target: K }[],
): T & Record<K, string> => {
    // 保留原有的函数实现逻辑,以下为示例占位代码
    const baseRecord = recordBuilder({});
    const localizedProps = propsMapper.reduce((acc, { target }) => {
        acc[target] = ""; // 替换为实际的本地化值获取逻辑
        return acc;
    }, {} as Record<K, string>);
    return { ...baseRecord, ...localizedProps };
};

效果验证

  1. 传入单个target时:
const bounties = buildLocalizedInfo(
    (record) => ({
        id: record['m_ID'],
    }),
    [{ target: 'name' }],
);
// bounties 的类型为:{ id: number; name: string }
  1. 传入多个target时:
const detailedBounties = buildLocalizedInfo(
    (record) => ({
        id: record['m_ID'],
        other: record['m_Other'],
    }),
    [{ target: 'name' }, { target: 'description' }],
);
// detailedBounties 的类型为:{ id: number; other: any; name: string; description: string }
// 若 record['m_Other'] 有明确类型(比如 string),则类型会自动推导为 { id: number; other: string; name: string; description: string }

原理说明

  • 泛型K会自动推断propsMapper中所有target字段的字符串字面量联合类型(比如'name' | 'description')。
  • Record<K, string>会生成一个以K中所有字符串为键、值类型为string的对象类型。
  • 通过T & Record<K, string>将基础记录类型和动态扩展的本地化属性类型交叉,得到最终的返回类型。

内容的提问来源于stack exchange,提问作者Sébastien Tromp

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:05:21