如何使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 }; };
效果验证
- 传入单个
target时:
const bounties = buildLocalizedInfo( (record) => ({ id: record['m_ID'], }), [{ target: 'name' }], ); // bounties 的类型为:{ id: number; name: string }
- 传入多个
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
相关产品推荐
相关产品推荐

