[英]How can I return the same type as I pass into a function in Typescript?
[英]How can I inject a type into a function in Typescript?
我有這個功能:
elem = (arr, property, num) => {
arr.forEach(function (elem, index) {
if (elem[property] === num)
return elem;
})
};
我可以通過某種方式使用泛型,以便可以將函數與type
一起調用,以便它返回特定type
例如:
exam = <IExam> elem(exams, 'abc', 3);
我認為這會起作用,但是我想知道是否可以通過某種方式將IExam
傳遞給該函數。
這可能是答案(有一個可行的示例 )
interface IExam {
ID: number;
}
var arr: any[] = [{}, {ID:1}, {ID: 2}];
var elem = <T>(arr, property, num) : T => {
var result: T = null;
arr.forEach(function (elm, index) {
if (elm[property] === num)
result = <T>elm;
return;
})
return result;
};
var myResult: IExam = elem<IExam>(arr, "ID", 1);
在這里我們可以對其進行測試(檢查操場,單擊運行 ) :
var resultPre = document.createElement('pre');
resultPre.innerText = JSON.stringify(myResult);
document.body.appendChild(resultPre);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.