[英]Copy a object properties to another in TypeScript, cause error TS2339
I use a extend()
function to extend a object:我使用一个
extend()
函数来扩展一个对象:
function extend(obj: Object, extension: Object) {
for (var key in obj) {
try {
extension[key] = obj[key];
} catch (e) {
console.error(e);
}
}
}
And there is a class Observer()
hava a method Update()
and a object check
which is HTMLInputElement
type.并且有一个类
Observer()
有一个方法Update()
和一个HTMLInputElement
类型的对象check
。
class Observer {
Update(value) { }
}
var check:HTMLInputElement = document.createElement("input");
I use extend()
function to extend checkbox
,so it would have the method Update()
.我使用
extend()
函数来扩展checkbox
,所以它会有方法Update()
。
extend(new Observer(), check);
check.Update = function(value) {
this.checked = value;
}
And then cause error TS2339: Property 'Update' does not exist on type 'HTMLInputElement'
然后导致错误 TS2339:
Property 'Update' does not exist on type 'HTMLInputElement'
How to Fixed this error?如何修复此错误? Change the
extend()
function?更改
extend()
函数?
Might be a good scenario for an intersection type ?对于交叉点类型来说可能是一个好场景?
function extend<T, U>(obj: T, extension: U) {
Object.keys(obj).forEach((key) => {
extension[key] = obj[key];
});
return extension as T & U;
}
var check: HTMLInputElement;
var extended = extend(new Observer(), check);
// example HTMLInputElement property use
extended.attributes;
// no compile error here either:
extended.Update = function(value) {
this.checked = value;
};
Is the following code snippet, what you are looking for?以下代码片段是您要查找的内容吗?
class Observer extends HTMLInputElement{
Update: any;
}
var check:Observer = <Observer>document.createElement("input");
check.Update = function(value) {
this.checked = value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.