使用Typescript描述具有动态添加属性的类

使用Typescript描述具有动态添加属性的类,typescript,knockout.js,Typescript,Knockout.js,我正在尝试将Typescript定义添加到一个现有的代码库中,该代码库恰好使用了Knockout库。代码包含一个非常常见的模式,如下所示: interface SomeProperties { // A bunch of properties } class ViewModel { // Some properties of my own... constructor(data: SomeProperties) { AddAllPropertiesTo

我正在尝试将Typescript定义添加到一个现有的代码库中,该代码库恰好使用了Knockout库。代码包含一个非常常见的模式,如下所示:

interface SomeProperties {
    // A bunch of properties
}

class ViewModel {
    // Some properties of my own...

    constructor(data: SomeProperties) {
        AddAllPropertiesToThis(data);
    }
}
其中
AddAllPropertiesToThis
获取数据对象并将其所有属性动态添加到
this

我不知道如何用Typescript来表达这个模式。这样说是有道理的

class ViewModel implements SomeProperties
但这需要手动将接口定义中的所有属性复制到类中


是否有任何方法可以在不必键入冗余属性的情况下完成此处所需的操作?

您可以在ViewModel中引入成员变量
data:SomeProperties

interface SomeProperties {
    // A bunch of properties
}

class ViewModel {
    data: SomeProperties;

    constructor(data: SomeProperties) {
        // deep copy the data
        this.data = { ...data };
    }
}

对我来说,通过与上面代码一样的组合方式而不是继承方式来实现这一点更有意义。
ViewModel
包含(has)
SomeProperties
。它不是SomeProperties的扩展(“是一种”关系)。

同意,组合而不是继承似乎是一个更好的主意。这将是一个很好的主意,但实际上并不可能——它会在太多地方改变API,使其变得不可行。对这些对象属性的任何现有引用(即使是在标记中,因为这是敲除)都必须更改。您曾经解决过这个问题吗?