Javascript methodname<;等角括号的用途是什么;字符串>;()打字稿
如果有任何关于它的教程,你能帮助我为什么我们在类型脚本中使用角括号吗?例如,我在这里给出了一些代码,我需要解释Javascript methodname<;等角括号的用途是什么;字符串>;()打字稿,javascript,angularjs,typescript,Javascript,Angularjs,Typescript,如果有任何关于它的教程,你能帮助我为什么我们在类型脚本中使用角括号吗?例如,我在这里给出了一些代码,我需要解释 export class HomePage { constructor(public navCtrl: NavController) { let a = this.testfunc<boolean>(4); console.log(a); } testfunc<T>(s) {
export class HomePage {
constructor(public navCtrl: NavController) {
let a = this.testfunc<boolean>(4);
console.log(a);
}
testfunc<T>(s) {
return s;
}
}
导出类主页{
构造函数(公共navCtrl:NavController){
设a=this.testfunc(4);
控制台日志(a);
}
testfunc(s){
返回s;
}
}
谢谢这些都是指示testfunc{return s;}
表示testfunc
接受泛型类型参数T
testfunc(4)
为该类型参数提供类型参数(boolean
)。在该示例中,由于testfunc
不使用t
,因此它没有做很多事情,但请考虑:
function foo(arg: string) {
let numbers: Array<number> = [];
numbers[0] = arg; // Error: Type 'string' is not assignable to type 'number'.
}
现在,foo
不知道numbers
包含什么,只知道它包含的内容将匹配arg
的类型。因此,这两个调用都是有效的:
foo<number>(4);
foo<string>("bar");
这些尖括号被称为泛型。泛型允许您为字段类型和类的方法定义占位符。
它只允许在以后定义类型
export class HomePage {
constructor(public navCtrl: NavController) {
let a = this.testfunc<boolean>(4);
console.log(a);
}
testfunc<T>(s){
return s;
}
}
导出类主页{
构造函数(公共navCtrl:NavController){
设a=this.testfunc(4);
控制台日志(a);
}
testfunc(s){
返回s;
}
}
对于testFunc
方法,您只需创建一个可以接受任何数据类型的方法。尖括号之间的T
称为类型参数
使用泛型给了你一些自由,而不是别的。例如,对于泛型方法,我可以传入任何类型作为其类型参数
函数Rand(值:T){
...
}
将
T
设置为string
意味着该函数中的每个T
都必须是一个字符串,其他类型也是如此。非常感谢@T.J.Crowder,我从很多天开始就试图理解,但现在已经很清楚了。谢谢
foo(4);
foo("bar");
export class HomePage {
constructor(public navCtrl: NavController) {
let a = this.testfunc<boolean>(4);
console.log(a);
}
testfunc<T>(s){
return s;
}
}