将 Typescript 对象扩展运算符与此关键字一起使用

Using Typescript object spread operator with this keyword

在我的代码中,我经常需要从 json 复制数据以在构造函数中实例化 class。

function append(dst, src) {
    for (let key in src) {
        if (src.hasOwnProperty(key) {
            dst[key] = src[key];
        }
    }
};


export class DataClass {
    id: number;
    title: string;
    content: string;
    img: null | string;
    author: string; 
    // no methods, just raw data from API
}


export class AdoptedClass1 extends DataClass {
    // has same fields as DataClass
    showcase: string;

    constructor (data: DataClass) {
        append(data, this);

        // do some stuff
    }
}


// similar code for AdoptedClass2 

我想知道是否可以用对象扩展运算符替换构造函数中的追加函数调用

根据您的需要,我更愿意使用 Object.assign(this, data) 而不是您自定义的 append 函数。尽管如此,请查看 documentation 以了解它的局限性。

回到您的主要问题:无法使用展开运算符来执行您想要的操作。许多人对该功能感兴趣,但如您所见here.

,它已被搁置

为了更接近您的要求,我们可以稍微重构您的代码:

export class DataClass {
    id: number
    title: string
    content: string
    img: null | string
    author: string
    constructor(data: DataClass) {
        Object.assign(this, data)
    }
}

export class AdoptedClass1 extends DataClass {
    showcase: string

    constructor (data: DataClass) {
        super(data)

        // do some stuff
    }
}

只需将 constructor 添加到数据 class 中,您就可以在儿童中使用 super(data),恕我直言,代码会更简洁。

您可以通过替换此行来使用对象展开运算符:

append(data,this)

用这条线

data = {...data, ...this};