Issue
Can you please help me if there have any tutorial on it why we use the angular brackets <> in type script for example I have given some code here I need explanation.
export class HomePage {
constructor(public navCtrl: NavController) {
let a = this.testfunc<boolean>(4);
console.log(a);
}
testfunc<T>(s) {
return s;
}
}
Thanks
Solution
Those are indicating generics. testfunc<T>(s){ return s; } means that testfunc accepts a generic type parameter T. testfunc<boolean>(4) provides a type argument (boolean) for that type parameter. In that example it doesn't do much of anything since testfunc doesn't use T, but consider:
function foo(arg: string) {
let numbers: Array<number> = [];
numbers[0] = arg; // Error: Type 'string' is not assignable to type 'number'.
}
That declares numbers as an array of number. Since arg is a string, you can't do numbers[0] = arg.
Compare with:
function foo<T>(arg: T) {
let numbers: Array<T> = [];
numbers[0] = arg; // Error
}
Now, foo doesn't know what numbers contains, just that whatever it contains will match the type of arg. So both of these calls are valid:
foo<number>(4);
foo<string>("bar");
I've included the type arguments in those calls for emphasis, but TypeScript can infer them much of the time:
foo(4);
foo("bar");
Answered By - T.J. Crowder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.