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

如何将SQLite查询结果反序列化为TypeScript类实例?

解决方案:将SQLite查询结果实例化为TypeScript类

问题根源

你用for...in遍历数组时,拿到的是数组的索引字符串(比如"0"、"1"),而非每行的数据对象,所以row.id自然无法获取到列值。

修正方案

1. 使用for...of遍历数组元素(基础版)

直接遍历数组中的每一行对象,转换为Obj类型:

export const GetAllObjs = (): Obj[] => {
  const query = db.prepare("SELECT * FROM ObjTable");
  // 断言查询结果的类型,匹配表结构
  const rows = query.all() as Array<{ id: number; name: string; amount: number }>;
  const objs: Obj[] = [];
  
  for (const row of rows) {
    objs.push({
      id: row.id,
      name: row.name,
      amount: row.amount
    } as Obj);
  }
  
  return objs;
};

2. 使用Array.map简化代码(推荐)

用数组的map方法直接转换,代码更简洁:

export const GetAllObjs = (): Obj[] => {
  const query = db.prepare("SELECT * FROM ObjTable");
  const rows = query.all() as Array<{ id: number; name: string; amount: number }>;
  
  return rows.map(row => ({
    id: row.id,
    name: row.name,
    amount: row.amount
  } as Obj));
};

3. 若Obj是类(而非接口),直接实例化

如果Obj是带有构造函数的类,比如:

class Obj {
  id: number;
  name: string;
  amount: number;

  constructor(id: number, name: string, amount: number) {
    this.id = id;
    this.name = name;
    this.amount = amount;
  }
}

可以直接在map中调用构造函数实例化:

export const GetAllObjs = (): Obj[] => {
  const query = db.prepare("SELECT * FROM ObjTable");
  const rows = query.all() as Array<{ id: number; name: string; amount: number }>;
  
  return rows.map(row => new Obj(row.id, row.name, row.amount));
};

关键说明

  • sqlite3的query.all()返回的是普通JavaScript对象数组,需要用类型断言(或定义匹配的接口)来让TypeScript识别行结构。
  • 遍历数组元素时,优先用for...of或数组迭代方法(map/forEach),for...in是用来遍历对象属性的,不适合遍历数组元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:17:34