【问题标题】:How do I extend a base interface dynamically?如何动态扩展基本接口?
【发布时间】:2022-01-17 09:14:57
【问题描述】:

我正在使用 react-query 并且有很多接受这些参数的 useQuery 钩子:

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

如何编写更通用的接口以接受任何或相当未知的附加接口?

所以是这样的:

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

UseQueryHookProps 的调用位置:

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

不知道怎么写?

【问题讨论】:

  • 为什么不直接写UseQueryHookProps&lt;MonitoringServiceClient&gt; &amp; {jobId: string}

标签: javascript typescript interface


【解决方案1】:

你不能用T扩展接口。为了做到这一点 - T 应该是静态已知的。

如果你想用T 扩展UseQueryHookProps,你应该使用type 语法而不是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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 2019-05-22
    • 2022-01-14
    相关资源
    最近更新 更多