繁体   English   中英

使用for..in的对象的Typescript复制属性

[英]Typescript copy properties of an object using for..in

我正在尝试使用for..in复制对象的属性,但出现错误:

类型“ Greeter [Extract]”不能分配给类型“ this [Extract]”。

任何想法如何解决这个问题?

class Greeter {
a: string;
b: string;
c: string;
// etc

constructor(cloned: Greeter) {

    for (const i in this) {
        if (cloned.hasOwnProperty(i)) {
            this[i] = cloned[i];
        }
    }
}

是打字稿游乐场中的示例。

谢谢!

问题是,类型this是不是Greeter它是多态的this类型 一个不幸后果是, i在你的for循环我输入的keyof thisGreeting可以使用索引keyof Greeting 这些看起来似乎是一回事,但是如果您认为可以派生Greeting ,则其中的keyof this可能包含更多的成员。 类似的讨论适用于索引操作的值。

编译器没有错, this可能比Greeter具有更多的密钥,因此不是100%安全的。

最简单的解决方法是使用一种类型的断言改变的类型this

class Greeter {
    a: string;
    b: string;
    c: string;
    // etc

    constructor(cloned: Greeter) {
        for (const i in this as Greeter) {
            if (cloned.hasOwnProperty(i)) {
                this[i] = cloned[i]
            }
        }

    }
}

或者,您可以遍历cloned对象:

class Greeter {
    a: string;
    b: string;
    c: string;
    // etc

    constructor(cloned: Greeter) {
        for (const i in cloned) {
            if (cloned.hasOwnProperty(i)) {
                this[i] = cloned[i]
            }
        }

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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