RyanP13
RyanP13

Reputation: 7743

How do I extend a base interface dynamically?

I am using react-query and have a lot of useQuery hooks that accept these parameters:

export interface UseQueryHookProps<K> {
  client: K;
  isEnabled?: boolean;
}

How would I write the interface to be more generic to accept any or rather unknown additional interface/s?

So something like this:

export interface UseQueryHookProps<K, T> extends T {
  client: K;
  isEnabled?: boolean;
}

Where UseQueryHookProps would be called:

export const useGetJob = ({
  client: monitoringService,
  isEnabled = true,
  jobId,
}: UseQueryHookProps<MonitoringServiceClient, {jobId: string}>) 

I am not sure how to write this?

Upvotes: 2

Views: 112

Answers (1)

You are not allowed to extend interface with T. In order to do that - T should be statically known.

If you want to extend UseQueryHookProps with T you should use type syntax instead of interface.

export interface UseQueryHookProps<K> {
  client: K;
  isEnabled?: boolean;
}

type ExtendHookProps<K, T> = UseQueryHookProps<K> & T

interface MonitoringServiceClient {
  tag: 'MonitoringServiceClient'
}

export const useGetJob = ({
  client: monitoringService,
  isEnabled = true,
  jobId,
}: ExtendHookProps<MonitoringServiceClient, { jobId: string }>) => {

}

Playground

Upvotes: 3

Related Questions