TypeScript 中 DynamoDB.QueryInput 报属性可能 undefined 的正确修复方式
无冗余判空的TypeScript DynamoDB参数类型适配方案
你遇到的报错根源不是运行时的空值风险,而是初始化时的显式类型标注导致TS丢弃了“两个Expression属性已被赋值”的事实。当你写const params: QueryInput = { ... }时,TS会完全套用QueryInput的官方类型定义,不管你实际传了什么值,两个可选的Expression属性都会被认定为属性值 | undefined类型,后续动态索引访问自然触发类型错误。
之前你加的那两行判空代码本质是完全冗余的:你初始化时已经给两个属性传入了非空初始值,运行时根本不可能走到属性为undefined的分支,报错只是TS的类型识别和实际逻辑脱节导致的,不是真实的运行时风险。
下面是两种符合规范、无需冗余判空、不需要重写SDK类型的实现方式:
方案一:延迟类型标注,利用TS自动类型推导
TS的自动推导会忠实保留你初始化传入的所有字段的实际存在状态,不需要提前把对象钉死成SDK的官方类型:
- 先构造基础参数字面量,不提前标注为
QueryInput类型 - 等所有动态字段修改完成后,最后再把构造完成的对象赋值给
QueryInput类型的变量,满足SDK的类型校验要求
对应代码实现:
// 先构造基础参数,不提前做类型标注,TS会自动推导出两个Expression属性为非空对象 const baseParams = { TableName: tableName, KeyConditionExpression: '#hashKey = :hashValue AND #rangeKey = :rangeValue', ExpressionAttributeNames: { '#hashKey': hashKey, '#rangeKey': rangeKey }, ExpressionAttributeValues: { ':hashValue': hashValue, ':rangeValue': rangeValue }, IndexName: indexName, Limit: fetchLimit, ScanIndexForward: true, ProjectionExpression: projectionItems.concat([documentKey]) } // 这一步没有类型报错:TS明确知道两个Expression属性是必然存在的非空对象 if (beforeDateCondition) { baseParams.FilterExpression = '#updatedAt < :updatedAt' baseParams.ExpressionAttributeNames['#updatedAt'] = 'updatedAt' baseParams.ExpressionAttributeValues[':updatedAt'] = beforeDateCondition } // 最后完成类型适配,传给SDK时通过类型校验 const params: DynamoDB.DocumentClient.QueryInput = baseParams
这种方式没有任何类型断言,完全靠TS的自动推导完成类型检查,是安全性最高的实现。
方案二:初始化时对必传的Expression属性做类型收窄
如果不想拆分变量,可以在对象初始化的阶段,直接给两个必传的Expression属性做类型收窄,去掉类型定义里的undefined可能性,不需要额外的运行时判空:
const params: DynamoDB.DocumentClient.QueryInput = { TableName: tableName, KeyConditionExpression: '#hashKey = :hashValue AND #rangeKey = :rangeValue', // 直接在初始化时锁定这两个字段为非空类型,TS会识别到这两个属性不存在undefined可能 ExpressionAttributeNames: { '#hashKey': hashKey, '#rangeKey': rangeKey } as NonNullable<DynamoDB.DocumentClient.QueryInput['ExpressionAttributeNames']>, ExpressionAttributeValues: { ':hashValue': hashValue, ':rangeValue': rangeValue } as NonNullable<DynamoDB.DocumentClient.QueryInput['ExpressionAttributeValues']>, IndexName: indexName, Limit: fetchLimit, ScanIndexForward: true, ProjectionExpression: projectionItems.concat([documentKey]) } // 这一步不会触发undefined报错 if (beforeDateCondition) { params.FilterExpression = '#updatedAt < :updatedAt' params.ExpressionAttributeNames['#updatedAt'] = 'updatedAt' params.ExpressionAttributeValues[':updatedAt'] = beforeDateCondition }
这里用到的NonNullable工具类型,只是把官方可选属性定义里的| undefined去掉,和你实际传入的初始值完全匹配,不存在类型欺骗的问题,也不需要额外加那两行判空代码。
内容的提问来源于stack exchange,提问作者cyberwombat
相关产品推荐
相关产品推荐

