[英]TypeScript: How to set object property in constructor (depending on object properties)
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);
这是很难理解你想什么从您的代码做的,例如这是什么item
,该构造函数得到的参数? 是Item
另一个实例还是其他类型?
此外,与所有者的全部关系还不清楚。
无论如何,您的类要么具有定义的属性,要么没有。
您当然可以在ctor中添加更多属性,而无需将它们定义为成员,但这会导致您可能希望避免的打字稿编译错误,例如:
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);
但是然后您绕过了编译器类型检查,如果要这样做,那么为什么还要打扰打字稿呢?
如果要避免让成员具有null
或undefined
您可以做的是对同一接口/基类使用不同的实现,并使用工厂函数根据接收到的数据创建正确的实现,例如:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.