【问题标题】:How to get properties of interface only if variable contains reference to a class that implements that interface?仅当变量包含对实现该接口的类的引用时,如何获取接口的属性?
【发布时间】:2025-11-30 00:25:01
【问题描述】:

我需要获取特定接口的对象的属性,该接口包含对类对象的引用。当我打印那个对象时,我得到了那个类的所有属性。

export interface IReporting
{
    Name: string | null;
    KeyValues: Array<KeyValue>;
}
export class AdminReport implements IReporting
{
    Id: number;
    UserIcon: string | null;
    Name: string | null;
    //Key-values
    KeyValues: Array<KeyValue>;
}
In component class:
let updated = <IReporting>(this.report);
console.log(updated);

应该期望看到: Name 和 KeyValues,而是获取 AdminReport 的所有属性

【问题讨论】:

  • 添加一些示例代码来说明你想要做什么
  • 但是我将此对象发送到服务器,我希望它自动发送该对象(接口)的所有属性,而无需我手动选择每个属性。

标签: typescript polymorphism


【解决方案1】:

使用类型断言不会改变底层运行时对象的任何内容。它只是通知编译器您希望report 具有接口定义的形状。

你必须创建一个只包含你想发送到服务器的属性的新对象:

let updated = <IReporting>{
    KeyValues: report.KeyValues,
    Name: report.Name
}

您可以创建一个仅包含报表属性的类,并将信息从另一个对象复制到该类。如果接口有很多属性,这是有道理的:

export class JustReporting implements IReporting
{
    // All proeprties must be initialized with null or another default so they appear when we call Object.getOwnPropertyNames
    Name: string | null = null;
    KeyValues: Array<KeyValue> = null;
    constructor(data: IReporting) {
        for (const prop of Object.getOwnPropertyNames(this)) {
            (<any>this)[prop] = (<any>data)[prop];
        }
    }
}

【讨论】:

  • 还添加了更自动化的方式来完成这个,也许对你有用:)
最近更新 更多