【问题标题】:Typescript : How to assign class and its members as one of the interface propertiesTypescript:如何将类及其成员分配为接口属性之一
【发布时间】:2021-04-20 03:44:39
【问题描述】:

在类型脚本中,我有一个接口和一个类。

接口的属性之一就是类本身。如何将类及其成员分配为接口的属性之一?

export interface ITest {
  _Id: string;
  _UserName: string;
   ***Criteria: Need to assign the class MyCriteria to this interface's property "Criteria"***
}

export class MyCriteria 
{
  _Name: string = "department";
  _Codes: string[]; // String array

  constructor(Name: string, Codes: string[]) {
    this._Name= Name;
   this._Codes= Codes;
  }
}

【问题讨论】:

    标签: typescript class interface


    【解决方案1】:

    您可以只使用MyCriteria 作为类型。

    export interface ITest {
      _Id: string;
      _UserName: string;
       Criteria: MyCriteria
    }
    
    export class MyCriteria 
    {
      _Name: string = "department";
      _Codes: string[]; // String array
    
      constructor(Name: string, Codes: string[]) {
        this._Name= Name;
       this._Codes= Codes;
      }
    }
    
    const test: ITest = {
        _Id: "",
        _UserName: "",
        Criteria: new MyCriteria("",[""])
    }
    
    test.Criteria._Codes = ["new codes"];
    

    【讨论】:

    • 你不需要typeofMyCriteria 本身就是一个类型。
    • 感谢您的回复,这种情况下如何赋值?我想分配 _Codes 值,该怎么做?
    • 添加了一个带有赋值的新对象。
    猜你喜欢
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 2023-04-08
    • 2019-09-22
    • 2016-12-08
    相关资源
    最近更新 更多