You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用DynamoDB数据?解决TypeScript类型报错问题

DynamoDB数据访问与TypeScript类型报错问题

数据库返回的示例数据:

{
    "Item": {
        "AlbumTitle": {
            "S": "Songs About Life"
        },
        "Awards": {
            "S": "10"
        },
        "Artist": {
            "S": "Acme Band"
        },
        "SongTitle": {
            "S": "Happy Day"
        }
    }
}

我原本想用data.Item.AlbumTitle.S访问专辑名称,但使用解构赋值时出现TypeScript报错:

import {GetItemCommand} from "@aws-sdk/client-dynamodb";

const getFromDb = async (albumTitle: string) => {
  const command = new GetItemCommand({
    TableName: "table-name",
    Key: {
      AlbumTitle: { S: albumTitle }
    }
  });

  return await client.send(command);
};

const dbRes = await getFromDb('some-album');
const {AlbumTitle, Awards, Artist, SongTitle} = dbRes?.Item;

IDE报错提示:

TS2339: Property AlbumTitle does not exist on type Record<string, AttributeValue> | undefined

假设能获取到正确的专辑数据,请问该如何使用这些数据?是否必须通过dbRes.Item.Artist.S这类方式访问?


解决方法与数据使用方式

1. 类型断言快速修复报错

TypeScript无法推断dbRes.Item的具体结构,你可以通过自定义接口+类型断言明确它的类型:

interface AlbumItem {
  AlbumTitle: { S: string };
  Awards: { S: string };
  Artist: { S: string };
  SongTitle: { S: string };
}

const dbRes = await getFromDb('some-album');
const {AlbumTitle, Awards, Artist, SongTitle} = dbRes?.Item as AlbumItem;

断言后即可正常通过AlbumTitle.S访问具体值。

2. 用unmarshall简化数据访问

AWS SDK自带unmarshall方法,能把DynamoDB的结构化数据转换成普通JS对象,无需每次写.S:

import {GetItemCommand, unmarshall} from "@aws-sdk/client-dynamodb";

const getFromDb = async (albumTitle: string) => {
  const command = new GetItemCommand({
    TableName: "table-name",
    Key: {
      AlbumTitle: { S: albumTitle }
    }
  });
  const response = await client.send(command);
  // 将DynamoDB格式转成普通对象
  return response.Item ? unmarshall(response.Item) : null;
};

const albumData = await getFromDb('some-album');
if (albumData) {
  // 直接访问属性,无需.S
  console.log(albumData.AlbumTitle, albumData.Artist);
}

这种方式更符合日常JS/TS的使用习惯,也能从根源避免类型报错。

3. 原生访问方式的正确性

如果不使用转换工具,确实需要通过dbRes.Item.Artist.S这类方式访问值——因为DynamoDB返回的是带类型标识的结构化数据,每个属性都包含类型字段(比如S代表字符串、N代表数字等),必须通过类型字段才能拿到实际值。

内容的提问来源于stack exchange,提问作者physicsboy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 20:12:11