![](/img/trans.png)
[英]Using destructuring/spreading to copy object with renamed properties 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 this
而Greeting
可以使用索引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.