如果类(例如WikipediaSearchResult
)在typescript中有一些属性,那么是否可以访问它们?也许这个问题有点幼稚,但我想知道是否可以编写以下代码而不使用重复的属性名:
function mergeTo(from:any, to:any={}, properties:Array<string>=[]) {
if (!!from) {
for (var property of properties) {
// no deep copy here ;-)
to[property] = from[property];
}
}
}
class WikipediaSearchResult /* implements IWikipediaSearchResult */ {
lang:string;
summary:string;
title:string;
wikipediaUrl:string;
constructor(obj?:any) {
mergeTo(obj, this, [
// --> How to avoid this list? <--
'lang', 'summary', 'title', 'wikipediaUrl'
]);
}
}
var result = new WikipediaSearchResult({
title: 'Zürich',
wikipediaUrl: 'https://en.wikipedia.org/wiki/Z%C3%BCrich'
});
console.log(result);
当然,也有一些第三方库,如underline.js,但它与
_.clone(...)
不同,因为我只想克隆特定属性,而忽略obj
分别提供的所有其他属性。另一种方法可能是使用例如
from
,还没有尝试过,但它将使用javascript prototype属性。最好使用typescript内部机制。我想到的一个想法是创建一个“虚拟”实例并读取其密钥。我想知道是否有人能想出更好的变种?
最佳答案
初始化类WikipediaSearchResult
的属性允许使用this
作为“模板”:
function mergeTo(from:any, to:any={}, properties:Array<string>=[]) {
// same as in question
}
function mergeTo2(from:Object, to:Object):Object {
// _.keys from underscore
return mergeTo(from, to, _.keys(to));
}
class WikipediaSearchResult {
lang:string = undefined;
summary:string = undefined;
title:string = undefined;
wikipediaUrl:string = undefined;
constructor(obj?:any) {
util.mergeTo2(obj, this);
}
}
var result = new WikipediaSearchResult({
title: 'Zürich',
wikipediaUrl: 'https://en.wikipedia.org/wiki/Z%C3%BCrich'
});
console.log(result);
仍在寻找其他变种…