Open betafcc opened 4 years ago
Thanks. I don't have much experience with TS. Lemme research on this a bit.
Nice! If it's useful then, here are some aditional info about those types:
With those, you can type transform as-is just by changing
transform(xml: string, template: object): Promise<any>;
to
transform<P extends Props>(xml: string, template: Template<P>): Promise<OutputOf<P>>;
My wrapper is called 'parse' and have inverted arguments just for personal preference.
The 'template' function does have a more important purpuse: you could use the typed transform
without it:
transform('', {
cache_key: '/HotelListResponse/cacheKey',
session_id: '/HotelListResponse/customerSessionId',
hotels: [
'//HotelSummary',
{
hotel_id: 'hotelId',
name: 'name',
rooms: [
'RoomRateDetailsList/RoomRateDetails',
{
room_name: 'roomDescription',
room_type_id: 'roomTypeCode'
}
]
}
]
})
And this will be well typed, but if you factor the entities:
const Hotel = {
hotel_id: 'hotelId',
name: 'name',
rooms: [
'RoomRateDetailsList/RoomRateDetails',
{
room_name: 'roomDescription',
room_type_id: 'roomTypeCode'
}
]
}
transform('', {
cache_key: '/HotelListResponse/cacheKey',
session_id: '/HotelListResponse/customerSessionId',
hotels: ['//HotelSummary', Hotel]
})
Then TS will complain that 'Hotel' entity in hotels: ['//HotelSummary', Hotel]
is not a Template
, that is because of the inference rules, for example, TS will see the Hotel.rooms
as a Array<string | {...}>
instead of a tuple of [string, {...}]
as it should be. One workaround would be to add as const
in the end of each entity declaration, but that raises other complexities around 'readonly' fields.
In the end, this aparentely 'dummy' function:
const template = <P extends Props>(props: P): Template<P> => props
Has the intent of helping the type system infer the plain object structure as a Template correctly without having to do a cumbersome as Template<{...}>
cast
It is possible to statically type the parsed type based on the template argument, I was meaning to do a PR but have no idea how to test it, plus, the definition of 'Template' is possibly incomplete, since I couldn't find doc on it.
I'm using these helpers:
With those, the example in README can be refactored to:
And TS can infer the parsed type:
Or it can be extracted:
Thanks for this awesome project btw