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

TypeScript/JavaScript中如何仅绑定类中存在的属性?

解决方案:仅保留Case类属性过滤多余字段

TypeScript的as类型断言只是编译时的类型提示,不会在运行时过滤掉多余字段。要真正只保留Case类中定义的属性,需要在运行时手动处理数据,以下是几种适合Angular+Supabase场景的实现方式:

1. 手动映射(简单直接)

直接遍历返回的数据,提取需要的属性创建新对象:

const result = await this.supabaseService.supabase
  .rpc('selectAllDBFunction', { "param": 'case' })
  .returns<Case[]>()

// 过滤出Case类的属性,忽略其他字段
const lstcase: Case[] = result.data?.map(item => ({
  caseName: item.caseName,
  caseColor: item.caseColor
})) || [];

2. 利用类的构造函数封装逻辑

给Case类添加构造函数,自动处理属性赋值:

export class Case {
  caseName: string;
  caseColor: string;

  constructor(obj: Partial<Case>) {
    // 可根据需求添加默认值避免null/undefined
    this.caseName = obj.caseName ?? '';
    this.caseColor = obj.caseColor ?? '';
  }
}

使用时直接通过构造函数实例化:

const result = await this.supabaseService.supabase
  .rpc('selectAllDBFunction', { "param": 'case' })
  .returns<Case[]>()

const lstcase: Case[] = result.data?.map(item => new Case(item)) || [];

3. 通用映射工具函数(适合多类复用)

如果有多个类需要类似的过滤逻辑,可以封装一个通用函数:

/**
 * 将原始数据数组映射为指定类的实例数组,仅保留类中定义的属性
 * @param data 原始数据库返回数据
 * @param cls 目标类的构造函数
 */
function mapToClass<T>(data: any[], cls: new () => T): T[] {
  return data.map(item => {
    const instance = new cls();
    // 遍历类的属性,仅复制存在的字段
    Object.keys(instance).forEach(key => {
      if (item.hasOwnProperty(key)) {
        instance[key as keyof T] = item[key];
      }
    });
    return instance;
  });
}

使用方式:

const result = await this.supabaseService.supabase
  .rpc('selectAllDBFunction', { "param": 'case' })
  .returns<Case[]>()

const lstcase: Case[] = result.data ? mapToClass(result.data, Case) : [];

额外优化建议

如果有权限修改Supabase的selectAllDBFunction函数,建议直接在数据库层面只返回需要的字段(比如caseName和caseColor),这样既能减少数据传输量,也省去前端的过滤逻辑,效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:42:53