From fff7940d1bd08f5b62a26249a8d2e71ccf77d310 Mon Sep 17 00:00:00 2001 From: David Chavez Date: Thu, 21 Sep 2023 18:59:04 +0200 Subject: [PATCH] fix(ts): Fix type inference in useTrackPlayerEvents (#2131) --- src/hooks/useTrackPlayerEvents.ts | 11 ++--------- src/interfaces/events/EventPayloadByEvent.ts | 13 +++++++++++-- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/src/hooks/useTrackPlayerEvents.ts b/src/hooks/useTrackPlayerEvents.ts index 444cef142..0a7e528ca 100644 --- a/src/hooks/useTrackPlayerEvents.ts +++ b/src/hooks/useTrackPlayerEvents.ts @@ -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[number]; +import type { EventPayloadByEventWithType } from '../interfaces'; /** * Attaches a handler to the given TrackPlayer events and performs cleanup on unmount @@ -14,11 +11,7 @@ type EventTypeFromArray = T[number]; */ export const useTrackPlayerEvents = < T extends Event[], - H extends ( - data: EventPayloadByEvent[EventTypeFromArray] & { - type: EventTypeFromArray; - } - ) => void + H extends (data: EventPayloadByEventWithType[T[number]]) => void >( events: T, handler: H diff --git a/src/interfaces/events/EventPayloadByEvent.ts b/src/interfaces/events/EventPayloadByEvent.ts index 631fdd687..2963cc493 100644 --- a/src/interfaces/events/EventPayloadByEvent.ts +++ b/src/interfaces/events/EventPayloadByEvent.ts @@ -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; @@ -48,4 +48,13 @@ export interface EventPayloadByEvent { [Event.MetadataChapterReceived]: AudioCommonMetadataReceivedEvent[]; [Event.MetadataTimedReceived]: AudioCommonMetadataReceivedEvent; [Event.MetadataCommonReceived]: AudioCommonMetadataReceivedEvent[]; -} +}; + +// eslint-disable-next-line +type Simplify = { [KeyType in keyof T]: T[KeyType] } & {}; + +export type EventPayloadByEventWithType = { + [K in keyof EventPayloadByEvent]: EventPayloadByEvent[K] extends never + ? { type: K } + : Simplify; +};