Skip to content

Commit

Permalink
fix(ts): Fix type inference in useTrackPlayerEvents (#2131)
Browse files Browse the repository at this point in the history
  • Loading branch information
dcvz authored Sep 21, 2023
1 parent 264ecc8 commit fff7940
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
11 changes: 2 additions & 9 deletions src/hooks/useTrackPlayerEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ import { useEffect, useRef } from 'react';

import { addEventListener } from '../trackPlayer';
import { Event } from '../constants';
import type { EventPayloadByEvent } from '../interfaces';

// Helper that gets the type of the event payload for a given event type
type EventTypeFromArray<T extends Event[]> = T[number];
import type { EventPayloadByEventWithType } from '../interfaces';

/**
* Attaches a handler to the given TrackPlayer events and performs cleanup on unmount
Expand All @@ -14,11 +11,7 @@ type EventTypeFromArray<T extends Event[]> = T[number];
*/
export const useTrackPlayerEvents = <
T extends Event[],
H extends (
data: EventPayloadByEvent[EventTypeFromArray<T>] & {
type: EventTypeFromArray<T>;
}
) => void
H extends (data: EventPayloadByEventWithType[T[number]]) => void
>(
events: T,
handler: H
Expand Down
13 changes: 11 additions & 2 deletions src/interfaces/events/EventPayloadByEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import type { RemoteSeekEvent } from './RemoteSeekEvent';
import type { RemoteSetRatingEvent } from './RemoteSetRatingEvent';
import type { RemoteSkipEvent } from './RemoteSkipEvent';

export interface EventPayloadByEvent {
export type EventPayloadByEvent = {
[Event.PlayerError]: PlayerErrorEvent;
[Event.PlaybackState]: PlaybackState;
[Event.PlaybackError]: PlaybackErrorEvent;
Expand Down Expand Up @@ -48,4 +48,13 @@ export interface EventPayloadByEvent {
[Event.MetadataChapterReceived]: AudioCommonMetadataReceivedEvent[];
[Event.MetadataTimedReceived]: AudioCommonMetadataReceivedEvent;
[Event.MetadataCommonReceived]: AudioCommonMetadataReceivedEvent[];
}
};

// eslint-disable-next-line
type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};

export type EventPayloadByEventWithType = {
[K in keyof EventPayloadByEvent]: EventPayloadByEvent[K] extends never
? { type: K }
: Simplify<EventPayloadByEvent[K] & { type: K }>;
};

0 comments on commit fff7940

Please sign in to comment.