首页 > 解决方案 > 打字稿修改嵌套类型

问题描述

我是打字稿的新手,不知道如何修改深层嵌套接口。

我有接口(从 graphql 模式生成),我想将其转换为新模型

看起来像这样

interface SeatMap{
    // other fields
    segments: {
        // other fields
        rows: { // <-- i want to add one more field to row type
            // other fields
            seats: { // <-- i want to add few new fields to seat type
                isAvailable: boolean;
                isAisle: boolean;
                // etc.
            }
        }
    }
}

比,我创建了两个新功能

addServiceFieldToSeats 接收 SeatMap 并返回带有修改后的座位类型的 SeatMap

和 addRowPartsToRows 接收 SeatMap 并返回带有修改的行类型的 SeatMap

然后通过 redux 中的 compose 函数创建新函数seatMapAdapter,但不知道如何解决打字稿错误

在此处输入图像描述

我知道我的函数将座位图行类型转换为新类型 RowWithParts 但addServiceFieldToSeats接收旧座位图类型

我如何描述每个 SeatMap 转换?

标签: typescripttypescript-typings

解决方案


经过几天的尝试,看起来我找到了解决方案:

type NestedModelTransition<OriginalType, Compare, ReplaceWith> = {
    [Key in keyof OriginalType]: OriginalType[Key] extends Compare
        ? ReplaceWith
        : NestedModelTransition<OriginalType[Key], Compare, ReplaceWith>
};

type SeatMapWithSeatService = NestedModelTransition<SeatMap_SeatMap, SeatMap_SeatMap_segments_decks_rows_seats, Seat>;

type SeatMapWithRowWithParts = NestedModelTransition<
    SeatMapWithSeatService,
    SeatMap_SeatMap_segments_decks_rows,
    RowWithParts
>;

推荐阅读