Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ts): Fix type inference in useTrackPlayerEvents #2131

Merged
merged 3 commits into from
Sep 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 }>;
};
Loading