gpt4 book ai didi

javascript - TypeScript:如何在构造函数中设置对象属性(取决于对象属性)

转载 作者:行者123 更新时间:2023-12-02 14:18:58 25 4
gpt4 key购买 nike

  1. 如果构造函数中的项目具有属性计数器 (item.counter),我需要在构造函数元素 (this.counter) 中创建此属性。仅当此属性具有 item 时如何创建此属性?
  2. 下一个问题是,如何按条件在构造函数中创建新属性(例如,如果 item.is_owner = true,我需要创建 this.owner = "Owner")

export class Item {
public counter: number;
public is_owner: boolean;
public owner: string;


constructor(item) {
this.counter = item.counter; // if item has counter, i need create this.counter
this.owner = "Owner"; // if item.is_owner == true ???
}
}

var element = new Item (item);

最佳答案

很难理解您想要从代码中执行的操作,例如 ctor 作为参数获取的这个 item 是什么?它是 Item 的另一个实例还是其他类型?
另外,与所有者的整个事情也不清楚。

无论如何,您的类要么具有已定义的属性,要么没有。
当然,您可以在构造函数中添加更多属性,而不将它们定义为成员,但这会导致您可能希望避免的 typescript 编译错误,例如:

class Point {
public x: number;

constructor(x: number, y: number) {
this.x = x;
this.y = y; // error: Property `y` does not exists on type `Point`
}
}

您可以通过转换为 any 来解决这个问题:

class Point {
public x: number;

constructor(x: number, y: number) {
this.x = x;
(this as any).y = y; // no error
}
}

但是这是一个问题:

let p = new Point(10, 5);
console.log(p.x);
console.log(p.y); // error: Property `y` does not exists on type `Point`

这里你可以使用 any: console.log((p as any).y); 但随后你会绕过编译器类型检查,如果你既然这样做了,那为什么还要费心 typescript 呢?

如果您想避免成员具有 nullundefined,您可以做的就是对同一接口(interface)/基类使用不同的实现并使用工厂函数根据收到的数据创建正确的实现,例如:

interface ItemData {
counter?: number;
}

class BaseItem {
static create(data: ItemData): BaseItem {
if (data.counter) {
return new ItemWithCounter(data);
}

return new BaseItem(data);
}

constructor(data: ItemData) {}
}

class ItemWithCounter extends BaseItem {
private counter: number;

constructor(data: ItemData) {
super(data);
this.counter = data.counter;
}
}

关于javascript - TypeScript:如何在构造函数中设置对象属性(取决于对象属性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38812952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com