Typescript复制对象的属性,用于..in
我正在尝试使用中的..复制对象的属性,但出现错误: 类型“Greeter[Extract]”不可分配给类型“this[Extract]” 有什么办法解决这个问题吗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)) {
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()]
将不起作用。此外,您的解决方案还具有运行时影响,就运行时成本而言,类型断言是免费的:)