代码之家  ›  专栏  ›  技术社区  ›  Ali Habibzadeh

当返回类型成员具有联合类型时,强制为方法中的成员确定返回类型

  •  1
  • Ali Habibzadeh  · 技术社区  · 8 年前

    采用以下方法:

    private async getJobExecutionIds(): Promise<Athena.ListQueryExecutionsOutput> {
        const params = { NextToken: this.nextToken, MaxResults: 50 };
        const response = await this.athena.listQueryExecutions(params).promise();
        if (response.QueryExecutionIds instanceof Array) {
          return response;
        }
        throw new Error("No Athena QueryExecutionIds");
    }
    

    response.QueryExecutionIds instanceof Array 为了保证我的用户能够安全地依赖 QueryExecutionIds: string[] | undefined

    但是,当我使用这种方法时:

    const executionIds = await this.getJobExecutionIds();
    

    我还是不能依靠 executionIds.QueryExecutionIds 作为 string[]

    1 回复  |  直到 8 年前
        1
  •  2
  •   Aviad Hadad    8 年前

    这里的问题是,虽然typescript type guards response.QueryExecutionIds instanceof Array ,实际上是一种全新的类型。

    QueryExecutionIds 不能没有定义。有两种选择,选择你最喜欢的:

    type ListQueryExecutionsOutputSafe = Athena.ListQueryExecutionsOutput & {QueryExecutionIds: string[]}
    interface ListQueryExecutionsOutputSafe extends Athena.ListQueryExecutionsOutput {
      QueryExecutionIds: string[];
    }
    

    下一步是定义一些自定义类型保护:

    const checkIfListQueryExecutionsOutputIsSafe = (obj: Athena.ListQueryExecutionsOutput): obj is ListQueryExecutionsOutputSafe => 
      !!obj.QueryExecutionIds; 
    

    最后:

      private async getJobExecutionIds(): Promise<ListQueryExecutionsOutputSafe> {
        const params = {NextToken: this.nextToken, MaxResults: 50};
        const response = await this.athena.listQueryExecutions(params).promise();
        if (checkIfListQueryExecutionsOutputIsSafe(response)) {
          return response;
        }
        throw new Error("No Athena QueryExecutionIds");
      }
    

    但为什么停在这里?让我们把所有东西都通用化:

    type TypeWithNotNullProp<T, SafeKey extends keyof T> = T & {[K in SafeKey]-?: T[K]}
    
    const checkSafeProp = <T, SafeKey extends keyof T>(obj: T, key: SafeKey): obj is TypeWithNotNullProp<T, SafeKey> => 
      !!obj[key];
    
    
    
      private async getJobExecutionIds(): Promise<ListQueryExecutionsOutputSafe> {
        const params = {NextToken: this.nextToken, MaxResults: 50};
        const response = await this.athena.listQueryExecutions(params).promise();
        if (checkSafeProp(response, 'QueryExecutionIds')) {
          return response;
        }
        throw new Error("No Athena QueryExecutionIds");
      }
    

    TypeWithNotNullProp checkSafeProp 在某些utils文件中,处理不同的api非常方便。

    推荐文章