代码之家  ›  专栏  ›  技术社区  ›  Gustavo Mendonça

类型脚本是否可以根据参数枚举推断类型?

  •  1
  • Gustavo Mendonça  · 技术社区  · 4 年前

    假设我有一个有3个参数的函数。第一个参数是我定义的枚举,第二个参数是具有基于枚举传递的值的形状的对象。第三个参数只是一个字符串。

    看看这个函数:

      async callApi<Response = any, Input = any>(
        op: ApiOperations,
        input: Input,
        functionName: string
      ): Promise<Response> {
        return this.lambda.invoke<Response>(functionName, {
          op,
          input
        });
      }
    

    您可以看到,我将此函数声明为泛型,并接收两种类型,并将默认值设置为any,这样就可以了。但是在这种情况下,每当我想调用这个函数时,我都必须手动指定输入和响应类型。问题是,我知道 ApiOperations 枚举,我只有一个输入类型和一个响应类型。

    所以我的问题是,typescript是否有任何方法可以根据枚举值推断类型?

    调用此函数的示例如下:

      async getChatRooms({ numberResults, siteId, startIndex }: GetChatRoomsInput): Promise<ChatRoom[]> {
        return this.api.callApi<ChatRoom[], GetChatRoomsInput>(ApiOperations.GetChatRooms, {
          siteId,
          numberResults,
          startIndex
        }, 'getChatRooms');
      }
    

    这很好,但我想做的是:

      async getChatRooms({ numberResults, siteId, startIndex }: GetChatRoomsInput): Promise<ChatRoom[]> {
        return this.api.callApi(ApiOperations.GetChatRooms, {
          siteId,
          numberResults,
          startIndex
        }, 'getChatRooms');
      }
    

    对于这种情况,typescript可以告诉我输入 GetChatRoomsInput 类型和 ChatRoom[] 作为响应类型。

    1 回复  |  直到 4 年前
        1
  •  2
  •   Alex Wayne    4 年前

    您只需要一个将枚举值映射到输入/响应类型的查找类型。例如:

    enum ApiOperations {
      A,
      B,
    }
    
    interface ApiOperationsLookup {
      [ApiOperations.A]: {
        input: { a: number }
        response: { a: string }
      }
    
      [ApiOperations.B]: {
        input: { b: number }
        response: { b: string }
      }
    }
    

    在这里 ApiOperationsLookup 是具有 ApiOperations 映射到特定的输入和响应类型。

    您可以通过以下方式获取输入类型:

    type Test = ApiOperationsLookup[ApiOperations.A]['input']
    // { a: number }
    

    现在你可以 callApi 如下所示:

      async callApi<T extends ApiOperations>(
        op: T,
        input: ApiOperationsLookup[T]['input'],
        functionName: string
      ): Promise<ApiOperationsLookup[T]['response']> {
        //...
      }
    

    这里是泛型参数 T 是来自 API运营 ,然后 input 并从该操作的查找映射中提取返回类型。

    现在,我想你已经预料到了:

    const aResponse = await instance.callApi(ApiOperations.A, { a: 123 }, 'aFuncName')
    // { a: string }
    
    const aBadResponse = await instance.callApi(ApiOperations.A, { b: 123 }, 'aFuncName')
    // type error on second argument
    
    const bResponse = await instance.callApi(ApiOperations.B, { b: 123 }, 'aFuncName')
    // { b: string }
    

    Playground


    另一个选项是跳过查找类型,而是在为枚举的每个成员创建函数签名时使用重载:

      // signature for each enum member
      async callApi(op: ApiOperations.A, input: { a: number }, functionName: string): Promise<{ a: string }>
      async callApi(op: ApiOperations.B, input: { b: number }, functionName: string): Promise<{ b: string }>
    
      // implementation
      async callApi(
        op: ApiOperations,
        input: unknown,
        functionName: string
      ): Promise<unknown> {
        //...
      }
    

    我认为这是一个更丑陋,更难维护个人,但这是一个意见的问题。

    Playground

    推荐文章