Typescript复制对象的属性,用于..in

Typescript复制对象的属性,用于..in,typescript,extract,Typescript,Extract,我正在尝试使用中的..复制对象的属性,但出现错误: 类型“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)) {

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

类型“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];
        }
    }
}
是typescript中的示例


谢谢

问题在于
的类型不是
迎宾员
而是。一个不幸的结果是,在for循环中输入的
i
作为
keyof this
Greeting
可以使用
keyof Greeting
索引。这些可能看起来是一样的,但是如果你认为代码< >问候语>代码>,的代码>键可能包含更多的成员。类似的讨论也适用于索引操作的值

编译器没有错,
的密钥可能比
问候者的密钥多,因此这不是100%安全的

最简单的解决方案是使用类型断言来更改此
的类型:

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]
            }
        }

    }
}
或者,您可以迭代克隆的
对象:

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]
            }
        }

    }
}

谢谢你,我对这个话题一无所知,我会解决的。似乎下面的方法也能奏效。。。for(const i in this){if(i in cert){this[i]=cert[i.toString()];}}@user2010955取决于您的编译器设置和
noImplictAny
cert[i.toString()]
将不起作用。此外,您的解决方案还具有运行时影响,就运行时成本而言,类型断言是免费的:)