It is unfortunate that the aws-sdk
library does not offer a Generic interface for setting the response type directly. This means you cannot simply do something like:
const person = await client.get<IPerson>(params).promise();
As mentioned by others, one workaround is to cast the type using:
const person = result?.Item as IPerson;
However, there is a risk with this approach as result?.Item
may not necessarily be of type IPerson
, and it involves tricking TypeScript into thinking it is.
Due to DynamoDB's schemaless nature, the item in your database could have any shape, potentially missing the required id
and name
attributes. It is essential to implement checks to handle unexpected data.
An effective method is to utilize a formatter that transforms your DynamoDB object into the desired response:
const client = new AWS.DynamoDB.DocumentClient();
interface IPerson {
id?: string,
name?: string
}
const format = (data: DynamoDB.DocumentClient.AttributeMap): IPerson {
return {
id: data?.id,
name: data?.name
};
}
const person = await client.get(params).promise();
const response = format(basket.Item); // maps DynamoDB.DocumentClient.AttributeMap => IPerson
DynamoDB.DocumentClient.AttributeMap
represents the response type of
client.get
, while other client methods such as scan may have different response types. Nevertheless, the concept remains consistent - mapping the client response to the required type.