繁体   English   中英

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

[英]TypeScript: How to set object property in constructor (depending on object properties)

  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); 

这是很难理解你想什么从您的代码做的,例如这是什么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`

您可以在这里使用anyconsole.log((p as any).y); 但是然后您绕过了编译器类型检查,如果要这样做,那么为什么还要打扰打字稿呢?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM