当我使用新的v3 aws-sdk做DynamoDB get时,我试图获得一个泛型类型作为我的OutputType的一部分。
函数如下:
public async getItem<T>(data: GetItemCommandInput) {
const command = new GetItemCommand({
...data
});
return await this.dbClient.send<GetItemCommand, T>(command);
}
Typescript不喜欢把T放在Send调用中。看看打字稿的定义,它是相当混乱的,我不明白他们在做什么。第一种Send
类型是ClientInput
类型,第二种是ClientOutput
类型。看着ClientOutput
的定义,我的下巴都要掉下来了:
ClientOutput extends MetadataBearer, ResolvedClientConfiguration extends SmithyResolvedConfiguration<HandlerOptions>> implements IClient<ClientInput, ClientOutput, ResolvedClientConfiguration>
…好吧,他们把我弄丢了。
通常情况下,我希望是这样的:
await this.dbClient.send<GetItemCommandInput, T>(command);
or
return await this.dbClient.send<GetItemCommandInput, GetItemCommandOutput<LegalAccount>>(command);
但是GetItemCommandOutput
不允许通用
看源代码键入我看到:
export interface GetItemOutput {
/**
* <p>A map of attribute names to <code>AttributeValue</code> objects, as specified
* by <code>ProjectionExpression</code>.</p>
*/
Item?: {
[key: string]: AttributeValue;
};
我的重点是,当我得到查询结果时,我知道输出中的Item是T类型的。是AWS忘记了,还是我漏掉了什么?文档完全没有预期的那么有用:(
我不确定这能帮助你,我有一个类似的问题,我终于找到了这个客户。
使用这个客户端,我可以执行类似于旧的aws-sdk
的查询。
您必须像这样设置DynamoDB客户端:
import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
const dynamoClient = new DynamoDBClient();
const ddbDocClient = DynamoDBDocumentClient.from(dynamoClient);
,你的函数可以变成这样:
import { GetCommand, GetCommandInput } from "@aws-sdk/lib-dynamodb";
// ...
public async getItem<T>(data: GetCommandInput) {
const command = new GetCommand({
...data
});
return await this.ddbDocClient.send(command) as Omit<GetCommandOutput, "Item"> & { Item: T };
}
如文档所述:
文档客户端通过抽象属性值的概念来简化在Amazon DynamoDB中处理项的工作。
然后你可以推断类型并期望它能正常工作。