将打字稿中索引器的键限制为仅来自联合的1个值

时间:2019-07-19 16:39:42

标签: typescript

我想指定一个动态对象键只能是联合的1个值:

export enum HTTPMethod {
  DELETE = 'DELETE',
  GET = 'GET',
  HEAD = 'HEAD',
  OTIONS = 'OPTIONS',
  PATCH = 'PATCH',
  POST = 'POST',
  PUT = 'PUT',
}

export type FetchData<TData> = (
  routeOrBody?: string | BodyInit | object,
  body?: BodyInit | object,
) => Promise<TData | undefined>

export type GraphqlFetch<TData> = (
  query: string,
  variables?: BodyInit | object,
) => Promise<TData>

export type AbortFetch = () => void

export interface FetchCommands<TData = any> {
  get: FetchData<TData>
  post: FetchData<TData>
  patch: FetchData<TData>
  put: FetchData<TData>
  del: FetchData<TData>
  delete: FetchData<TData>
  query: GraphqlFetch<TData>
  mutate: GraphqlFetch<TData>
  abort: AbortFetch
}

export interface UseFetchBaseResult<TData = any> {
  data: TData | undefined
  loading: boolean
  error: Error
}

export type RestFetchMethods =
  | 'get'
  | 'post'
  | 'patch'
  | 'put'
  | 'del'
  | 'delete'

export type GraphqlFetchMethods = 'query' | 'mutate'

export type FetchRequest<TData> = {
  [key in keyof FetchCommands<TData>]: key extends RestFetchMethods
    ? FetchData<TData>
    : key extends GraphqlFetchMethods
    ? GraphqlFetch<TData>
    : AbortFetch
}

export type DestructuringCommands<TData> = [
  TData | undefined,
  FetchCommands<TData>,
]

export type ObjectDestructure<
  TKey extends keyof FetchCommands,
  TData
> = UseFetchBaseResult<TData> & { [key: TKey]: FetchRequest<TData>[TKey] }

具体来说就是这种类型:

export type ObjectDestructure<
  TKey extends keyof FetchCommands,
  TData
> = UseFetchBaseResult<TData> & { [key: TKey]: FetchRequest<TData>[TKey] }

我希望Tkey是联合中的1值,而不是映射类型,但是[key: TKey]出现

错误
  

索引签名参数类型必须为“字符串”或“数字”。

Here是一个带有代码的游乐场

1 个答案:

答案 0 :(得分:0)

我相信[key in keyof TKey] solves your problem