[英]Typescript copy properties of an object using for..in
I'm trying to copy the properties of an object using for..in but I got the error: 我正在尝试使用for..in复制对象的属性,但出现错误:
Type 'Greeter[Extract]' is not assignable to type 'this[Extract]'. 类型“ Greeter [Extract]”不能分配给类型“ this [Extract]”。
Any ideas how to solve this? 任何想法如何解决这个问题?
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];
}
}
}
Here is the sample in the typescript playground. 这是打字稿游乐场中的示例。
Thanks! 谢谢!
The problem is that the type of this
is not Greeter
it's the polymorphic this
type . 问题是,类型
this
是不是Greeter
它是多态的this
类型 。 An unfortunate consequence is that the i
in your for loop i typed as keyof this
while Greeting
can be indexed using a keyof Greeting
. 一个不幸后果是,
i
在你的for循环我输入的keyof this
而Greeting
可以使用索引keyof Greeting
。 These may seem like the same thing, but if you consider that Greeting
can be derived, keyof this
could potentially contain a lot more members. 这些看起来似乎是一回事,但是如果您认为可以派生
Greeting
,则其中的keyof this
可能包含更多的成员。 A similar discussion applies to the value of the indexing operation. 类似的讨论适用于索引操作的值。
The compiler is not wrong, this
may have more keys than Greeter
so this is not 100% safe. 编译器没有错,
this
可能比Greeter
具有更多的密钥,因此不是100%安全的。
The simplest solution is to use a type assertion to change the type of this
: 最简单的解决方法是使用一种类型的断言改变的类型
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]
}
}
}
}
Or you can iterate over the cloned
object: 或者,您可以遍历
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.