使用 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];
}
}
}
Here 是 typescript playground 中的示例。
谢谢!
问题是 this
的类型不是 Greeter
,而是 polymorphic this
type。一个不幸的结果是,我在 for 循环中键入的 i
为 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]
}
}
}
}
我正在尝试使用 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];
}
}
}
Here 是 typescript playground 中的示例。
谢谢!
问题是 this
的类型不是 Greeter
,而是 polymorphic this
type。一个不幸的结果是,我在 for 循环中键入的 i
为 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]
}
}
}
}