【问题标题】:Optional Parameters in Class Constructors in TypeScriptTypeScript 类构造函数中的可选参数
【发布时间】:2020-04-19 15:08:24
【问题描述】:

有没有办法减轻 TypeScript 中可选参数的顺序?我目前正在上课

export default class Area {
    private name: string;
    private description: string;
    private item?: Item;
    private hazard?: Hazard;

    constructor(name: string, description: string, item?: Item, hazard?: Hazard) {
        this.name = name;
        this.description = description;
        this.item = item;
        this.hazard = hazard;
    }
}

对于这个 Area 类,我需要 namestring 参数,但不需要 itemhazard 参数。我尝试通过以下方式实例化一个 Area 对象:

let item = new Item(); // had required parameters, but not important for now
let hazard = new Hazard(); // had required parameters, but not important for now

let area = new Area("test", "test"); // works as expected
let area1 = new Area("test", "test", item); // works as expected
let area2 = new Area("test", "test", hazard); // DOES NOT WORK as expected
let area3 = new Area("test", "test", item, hazard); // works as expected

尽管hazarditem 是可选的,但如果我想省略item,我需要为第三个参数传入undefined。有没有办法减轻或放弃这种行为,我们可以传入与任何可选参数匹配的第三个参数?

【问题讨论】:

  • 不,这在 javascript/typescript 中是不可能的。您可以做的是更改构造函数以接受 { name: string, description: string, item?: Item, hazard?: Hazard } 之类的对象

标签: typescript constructor


【解决方案1】:

Typescript 完成的类型检查在 Typescript 中存在——它在编译后的 Javascript 中不存在,因此如果允许,Javascript 将无法确定哪个你实际上试图通过的论点。

相反,传递一个可选的对象,它可能具有itemhazard 属性:

class Item{}
class Hazard{}

export default class Area {
    private name: string;
    private description: string;
    private item?: Item;
    private hazard?: Hazard;

    constructor(
      name: string,
      description: string,
      obj: { item?: Item, hazard?: Hazard } = {}
    ) {
        this.name = name;
        this.description = description;
        if (obj.item) this.item = obj.item;
        if (obj.hazard) this.hazard = obj.hazard;
    }
}

const item = new Item();
const hazard = new Hazard();

const area = new Area("test", "test"); 
const area1 = new Area("test", "test", { item });
const area2 = new Area("test", "test", { hazard });
const area3 = new Area("test", "test", { item, hazard });

【讨论】:

猜你喜欢
  • 2021-03-12
  • 2019-02-26
  • 1970-01-01
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 2017-06-14
  • 1970-01-01
相关资源
最近更新 更多