For example I have a type EventMapping which is a map "eventName -> eventData". I need to store emitted events in a list. Thus I want to transform this map to type Event, so I can't push data of incorrect type into the events list.
// type which i have
type EventMapping = {
click: {
position: Point;
};
scroll: {
top: number;
bottom: number;
};
}
// type which i want to get
type Event = {
type: 'click';
data: {
position: Point;
};
} | {
type: 'scroll';
data: {
top: number;
bottom: number;
};
}
// usage example
const events: Event[] = [];
// ok
events.push({
type: 'scroll',
data: {
top: 0,
bottom: 0,
}
});
// error
events.push({
type: 'click',
data: {
top: 0,
bottom: 0,
}
});