![](/img/trans.png)
[英]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.