I need the same data served in these two types
type DataMap = {
id001: 'name1',
id002: 'name2',
id003: 'name3',
....
}
type DataTuple = [
{id: 'id001', name: 'name1'},
{id: 'id002', name: 'name2'},
{id: 'id003', name: 'name3'},
...
]
I would like to only declare this type once and have a single source of truth, But I cannot figure out a utility type function that translates the type from an object to a tuple.
ideally I would like to do something like this:
type DataMap = {
id001: 'name1',
id002: 'name2',
id003: 'name3',
....
};
type DataTuple = MapToTuple<DataMap>;
// or
type DataTuple = [
{id: 'id001', name: 'name1'},
{id: 'id002', name: 'name2'},
{id: 'id003', name: 'name3'},
...
];
type DataMap = TupleToMap<DataTuple>;
Are either of these functions MapToTuple<T>
or TupleToMap<T>
possible?
For TypeScript 4.1+ you can implement
TupleToMap
like this, assuming you know that theid
property should be the key and thename
property should be the value:The above uses key remapping which was introduced in TS 4.1. For earlier versions you could write it this way instead:
For
MapToTuple
it's not clear where you intend to get the ordering of the tuple from. It might be obvious to a human being that the entry withid001
should come before the entry withid002
, but for the compiler I'm not sure if it's worth trying to get that across. I will circle back if I come up with something not crazy.Playground link to code