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

如何为angular-gridster2的GridsterItem接口添加自定义属性?

解决angular-gridster2扩展GridsterItem接口的问题

方案1:类型断言直接访问

当你从组件获取到GridsterItem实例后,直接将其断言为你的自定义接口类型,就能访问新增属性:

// 示例:获取当前激活的item并断言
const activeItem = this.gridster.getActiveItem();
const customItem = activeItem as GridsterItemCustomInterface;
// 此时可正常访问customItem.property1、customItem.property2

方案2:声明合并扩展原有接口

创建一个.d.ts类型声明文件(比如gridster-extensions.d.ts),通过TypeScript的声明合并特性,直接扩展包内的原有接口:

import { GridsterItemComponentInterface } from 'angular-gridster2';

declare module 'angular-gridster2' {
  interface GridsterItemComponentInterface {
    property1?: boolean;
    property2?: Config;
  }
}

确保该文件被tsconfig.json的include数组包含,之后项目中所有使用GridsterItemComponentInterface的地方,都会自动带上你新增的两个属性,无需手动断言。

方案3:包装数据分离存储

如果以上两种方式不适用,可以创建包装对象,将原有GridsterItem和自定义属性绑定存储:

interface WrappedGridsterItem {
  baseItem: GridsterItemComponentInterface;
  property1?: boolean;
  property2?: Config;
}
// 维护这个包装对象数组来管理数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 04:17:03