这里的问题是,虽然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非常方便。