简体   繁体   中英

How can I inject a type into a function in Typescript?

I have this function:

elem = (arr, property, num) => {
    arr.forEach(function (elem, index) {
        if (elem[property] === num)
            return elem;
    })
};

Is there some way with generics that I can make it so the function can be called along with a type so that it returns a specific type

For example:

exam = <IExam> elem(exams, 'abc', 3);

I think this will work but I wonder if I could pass in IExam into the function somehow.

This could be the answer (there is a working example )

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);

and here we can test it (check the playground, click run ) :

var resultPre  = document.createElement('pre');
resultPre.innerText = JSON.stringify(myResult);

document.body.appendChild(resultPre);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM