Typescript - อ็อบเจ็กต์อาจจะเป็นค่า undefined - วิธีที่ถูกต้องในการ "แก้ไข" การกำหนดชนิด
ฉันกำลังใช้ aws dynamodb กับการเรียกนี้:
const params: DynamoDB.DocumentClient.QueryInput = {
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])
}
// These 2 ridiculous lines are necessary to get rid of error
if (!params.ExpressionAttributeNames) params.ExpressionAttributeNames = {}
if (!params.ExpressionAttributeValues) params.ExpressionAttributeValues = {}
if (beforeDateCondition) {
params.FilterExpression = '#updatedAt < :updatedAt'
params.ExpressionAttributeNames['#updatedAt'] = 'updatedAt'. // ERROR HERE
params.ExpressionAttributeValues[':updatedAt'] = beforeDateCondition // ERROR HERE
}
ถ้าฉันไม่ตรวจสอบและกำหนด ExpressionAttributeNames และ ExpressionAttributeValues ทันทีหลังจากที่ฉันกำหนดพวกมันจริง ๆ TS จะให้ข้อผิดพลาดในสองบรรทัดสุดท้ายเกี่ยวกับการที่มันอาจจะไม่ถูกกำหนด
ฉันเข้าใจว่า ExpressionAttributeValues และ ExpressionAttributeNames ไม่จำเป็นต้องใช้ (ประเภทคือ ExpressionAttributeNames?: ExpressionAttributeNameMap;) แต่ฉันจะแก้ไขมันโดยไม่ต้อง:
- เขียนโค้ดที่ทำให้ฉันรู้สึกอึดอัด
- เขียนใหม่คำจำกัดความของตัวเอง
DynamoDB.DocumentClient.QueryInput
วิธีที่ถูกต้องที่นี่คืออะไร?