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

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

本文关键字:属性 对象 取决于 设置 构造函数 TypeScript      更新时间:2023-09-26
  1. 如果构造函数中的项有属性counter(item.counter(,我需要在构造函数元素(this.counter(中创建此属性。只有当此属性有项时,如何创建此属性
  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的另一个实例还是另一种类型
此外,与所有者的整个事情还不清楚。

在任何情况下,您的类要么有已定义的属性,要么没有
当然,您可以在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呢?

如果您想避免成员具有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;
    }
}