打字稿修改嵌套类型

时间:2019-11-23 14:45:27

标签: typescript typescript-typings

我是打字稿的新手,无法弄清楚如何修改深层嵌套的接口。

我有接口(由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,但不知道如何解决打字稿错误

enter image description here

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

我如何描述每个SeatMap转换?

1 个答案:

答案 0 :(得分:0)

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

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
>;