如何为嵌套TypeScript类型添加新类型
解决方案:修改嵌套TypeScript类型以添加属性
核心问题分析
你之前的写法无效是因为直接在顶层类型做交叉操作,而目标属性是嵌套在Match -> info -> participants数组的元素里,顶层交叉只会给Match本身添加属性,无法修改深层嵌套的结构。
正确实现步骤
1. 定义增强后的Participant类型
直接利用已有类型做交叉,避免重复声明属性:
export type ParticipantWithAssets = Participant & ItemsAsset;
2. 重新定义包含增强Participant的Info类型
用Omit工具类型保留原Info的其他属性,仅替换participants的元素类型:
export type InfoWithAssetParticipants = Omit<Info, 'participants'> & { participants: ParticipantWithAssets[]; };
3. 生成最终的Match类型
同样用Omit替换原Match的info属性为新的InfoWithAssetParticipants:
export type MatchWithItemAssetInParticipant = Omit<Match, 'info'> & { info: InfoWithAssetParticipants; };
使用示例
处理API返回数据并添加资产属性的函数可以这样写,TypeScript会正确识别返回值类型:
function enrichMatchWithItemAssets(rawMatch: Match): MatchWithItemAssetInParticipant { return { ...rawMatch, info: { ...rawMatch.info, participants: rawMatch.info.participants.map(participant => ({ ...participant, itemAsset0: `http://img/item/${participant.item0}.png`, itemAsset1: `http://img/item/${participant.item1}.png`, itemAsset2: `http://img/item/${participant.item2}.png`, itemAsset3: `http://img/item/${participant.item3}.png`, itemAsset4: `http://img/item/${participant.item4}.png`, itemAsset5: `http://img/item/${participant.item5}.png`, itemAsset6: `http://img/item/${participant.item6}.png`, })) } }; }
内容的提问来源于stack exchange,提问作者Carlos Figueroa
相关产品推荐
相关产品推荐

