我想使用像这样带有
DynamoDB
的类型。
interface Custom {
id: string,
token: string,
}
const { Item }:GetItemOutput & { Item: Custom } = await DYNAMO_DB.get(params).promise();
我的 IDE 发出此警报。
类型“PromiseResult”不可分配给类型“GetItemOutput & { Item: Custom; }'。 类型“PromiseResult”不可分配给类型“{ Item: Custom;” }'。 属性“Item”的类型不兼容。 类型“AttributeMap”缺少类型“自定义”中的以下属性:id、tokents(2322)
如何将 typescript 与 Dynamodb 一起使用?
您收到的实际对象类型是
PromiseResult
,因此以下内容将起作用
const result:PromiseResult = await DYNAMO_DB.get(params).promise();
但你并没有获得很大的好处,所以我会保留它
const result = await DYNAMO_DB.get(params).promise();
使用 TypeScript 并不意味着你必须在任何地方使用类型
我认为这对你有用
interface Custom {
id: string,
token: string,
[key: string]: AttributeValue | string
}
const {Item} = await DYNAMO_DB.get(params).promise();
const ItemWithCustomType = (Item as Custom);
ItemWithCustomType.id
您可以使用处理类型(及更多)的库,而不是直接调用
DynamoDBDocument.get()
。
npm 包 dynamo-repo 使用起来非常简单,重量轻,你不需要担心转换。所以你的代码看起来像这样:
import { DBItemBase} from "dynamo-repo";
interface Custom extends DBItemBase {
id: string,
token: string,
}
const customItem = await customRepo.findItem({ id: "<custom-id-value>" });
const
customItem
已经是类型 Custom
👏😊
您只需创建
customRepo
一次:
import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb";
import { Custom } from "<path to your interface>";
import { Repo } from "dynamo-repo";
export class CustomRepo extends Repo<Custom, "id"> { /* "Custom" is the interface we created above */
constructor(ddbDocClient: DynamoDBDocument) {
super(ddbDocClient, "custom", "id"); /* "custom" is the table name */
this.setProjectionExpression([ /* Set all "Custom" attributes that are persisted in the table */
"id",
"token",
]);
}
}
然后通过您的 DynamoDBDocument 实例化它:
const customRepo = new CustomRepo(DYNAMO_DB);
addItem()
、updateItem()
、updateExpressionItem()
和 searchItems()
,而且它们都非常易于使用。