[英]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);
It's hard to understand what you're trying to do from your code, for example what's this item
that the ctor gets as a parameter? 这是很难理解你想什么从您的代码做的,例如这是什么
item
,该构造函数得到的参数? is it another instance of Item
or another type? 是
Item
另一个实例还是其他类型?
Also, the whole thing with the owner isn't clear. 此外,与所有者的全部关系还不清楚。
In any case, your class either has a defined property or doesn't. 无论如何,您的类要么具有定义的属性,要么没有。
You can of course add more properties in the ctor without defining them as members but that will cause typescript compilation errors which you probably prefer to avoid, for example: 您当然可以在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`
}
}
You can solve that with casting to any
: 您可以通过强制转换为
any
方法解决此问题:
class Point {
public x: number;
constructor(x: number, y: number) {
this.x = x;
(this as any).y = y; // no error
}
}
But then this is a problem: 但这是一个问题:
let p = new Point(10, 5);
console.log(p.x);
console.log(p.y); // error: Property `y` does not exists on type `Point`
Here to you can use any
: console.log((p as any).y);
您可以在这里使用
any
: console.log((p as any).y);
but then you bypass the compiler type checking and if you're doing that then why bother with typescript at all? 但是然后您绕过了编译器类型检查,如果要这样做,那么为什么还要打扰打字稿呢?
What you can do if you want to avoid having the member with null
or undefined
is to have different implementations of the same interface/base class and use a factory function to create the right implementation based on the received data, something like: 如果要避免让成员具有
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.