If I have these three distinct objects:
{
id: 1,
time: 1000,
type: 'A',
data: { a: 'one' }
}
{
id: 2,
time: 1001,
type: 'B',
data: { b: 123 }
}
{
id: 3,
time: 1002,
type: 'C',
data: { c: 'three', d: 123 }
}
and need to define a function like this:
function createEvent<TData,TEvent>(id: number, time: number, TData data): TEvent {}
What should my types be in order to successfully implement createEvent
? It seems that a combination of intersection, union, and generics will be needed.
For example, let's consider the following type definitions:
type InfoA = {a: string}
type InfoB = {b: number}
type InfoC = {c: string, d: number}
type EventTypeHeader = {id: number, time: number}
type EventTypeA = EventTypeHeader & { category: 'A', data: InfoA}
type EventTypeB = EventTypeHeader & { category: 'B', data: InfoB}
type EventTypeC = EventTypeHeader & { category: 'C', data: InfoC}
type CustomEvent = EventTypeA | EventTypeB | EventTypeC
function createEvent<T extends CustomEvent, U extends InfoA|InfoB|InfoC>(
id: number, time: number, data: U): CustomEvent
{
return {
id: id
time: time
type: 'something needs to go here?'
data: data
}
}
I seem to be struggling with understanding when to use union types and how to effectively apply generic types.
Thank you!