I am working with two TypeScript definitions:
interface Snapshot {
guild: Guild;
channels: ChannelsDataModel;
roles: RolesDataModel;
emojis: EmojisDataModel;
stickers: StickersDataModel;
permissionOverwrites: PermissionOverwritesDataModel;
bans: BansDataModel;
metadata: SnapshotMetadata;
}
type SerializedSnapshot = { [Property in keyof Snapshot]: string };
When serializing Snapshot
, all properties are converted to strings using JSON.stringify()
. The type SerializedSnapshot
represents this serialization process.
However, when creating the serialized object, I find myself repeating code:
function serializeSnapshot(snapshot: Snapshot): SerializedSnapshot {
function stringify(value: any): string {
return JSON.stringify(value, null, 2);
}
return {
guild: stringify(snapshot.guild),
channels: stringify(snapshot.channels),
roles: stringify(snapshot.roles),
emojis: stringify(snapshot.emojis),
stickers: stringify(snapshot.stickers),
permissionOverwrites: stringify(snapshot.permissionOverwrites),
bans: stringify(snapshot.bans),
metadata: stringify(snapshot.metadata),
};
}
The repetitive nature of the object creation process is a concern for me. I wish there was a way to use the map()
function to map one property of an object to another object with the same property names but different values. This would be defined by a mapping function. Essentially, a method to tell TypeScript that the resulting object has the same property names but different values based on the mapping function.
Is there a way to achieve this within TypeScript's type system?