TypeScript:如何在构造函数中设置对象属性(取决于对象属性)
TypeScript: How to set object property in constructor (depending on object properties)
- 如果构造函数中的项有属性counter(item.counter(,我需要在构造函数元素(this.counter(中创建此属性。只有当此属性有项时,如何创建此属性
- 下一个问题是,如何在构造函数中按条件创建新属性(例如,如果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
的另一个实例还是另一种类型
此外,与所有者的整个事情还不清楚。
在任何情况下,您的类要么有已定义的属性,要么没有
当然,您可以在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);
,但您可以绕过编译器类型检查,如果您正在这样做,那么为什么要麻烦使用typescript呢?
如果您想避免成员具有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;
}
}
相关文章:
- 为什么我可以在Array属性对象中找到Javascript Array for Each方法
- 使用onclick调用属性对象函数
- 嵌套为..in 循环,列出多维对象的属性(对象)
- 动态属性对象 - JSON
- 在不使用隔离范围angularjs自定义指令的情况下获取属性对象
- 通过属性传递属性/对象.Javascript
- Javascript:属性/对象的类型
- 访问JSON中的属性(对象)
- 属性对象Javascript不是用Jquery Deferred设置的
- 无法读取属性'#<对象>'未定义的获取错误
- Twitter中多属性对象的子字符串匹配
- 无法设置'data'属性'对象'标记.(只IE8)
- 更新数据属性对象属性值
- 将属性对象的选定对象从原型推入数组
- 将单个属性对象字面量的数组转换为仅包含其值的数组的最佳方法
- 寻找一种更简单的方法来检查是否多个属性&对象中的方法是未定义的
- 主干模型:带有get方法的空属性,但在属性对象中
- 如何赋值给"text"someText"属性对象在动能js
- Angularjs的数据绑定与数据属性对象
- 如何将一个嵌套的javascript对象转换为只有一级属性对象