javascript 使用泛型的动态类型

nhaq1z21  于 11个月前  发布在  Java
关注(0)|答案(1)|浏览(82)
export const createBill = /* GraphQL */ `mutation CreateBill(
  $input: CreateBillInput!
  $condition: ModelBillConditionInput
) {
  createBill(input: $input, condition: $condition) {
    periodStart
    periodEnd
    energy
    senderId
    receiverId
    metering_point_number
    file_key
    customer_number
    bill_number
    paid
    interval
    id
    createdAt
    updatedAt
    __typename
  }
}
` as GeneratedMutation<
  APITypes.CreateBillMutationVariables,
  APITypes.CreateBillMutation
>;

字符串
我有一个graphql查询,它是自动生成的。
现在我尝试创建一个函数,它接受字符串createBill和变量。变量是CreateBillMutationVariables,返回类型应该是CreateBillMutation
我该怎么做?

import * as mutations from '@/src/graphql/mutations'

export const apiQuery = <
  T extends keyof typeof mutations,
  F extends (typeof mutations)[T]
>(
  query: T,
  variables: F
) => {
  return API.graphql(graphqlOperation(query, variables))
}


我试过这个,它适用于查询,但不适用于变量。


的数据
编辑:

import * as mutations from '@/src/graphql/mutations'

export const apiQuery = <
  T extends keyof typeof mutations,
  F extends (typeof mutations)[T]['__generatedMutationInput']
>(
  query: T,
  variables: F
) => {
  return API.graphql(graphqlOperation(query, variables))
}

apiQuery('createBill', {input:{}})


现在看起来好多了,但问题是我的变量现在接受input,然后是实际的变量,我如何输入它,它只接受变量。

bihw5rsg

bihw5rsg1#

如果我正确理解了你想要的,你应该像这样修改你的函数签名:

export const apiQuery = <
  T extends keyof typeof mutations,
  F extends (typeof mutations)[T]['__generatedMutationInput']['input']
>(
  query: T,
  variables: F
)

字符串
虽然我对使用__generatedMutationInput有疑问,但可能有更干净的解决方案。

相关问题