如果有任何关于它的教程,你能帮我吗?例如,为什么我们在类型脚本中使用尖括号<>,我在这里给出了一些代码,我需要解释。
export class HomePage {
constructor(public navCtrl: NavController) {
let a = this.testfunc<boolean>(4);
console.log(a);
}
testfunc<T>(s) {
return s;
}
}
谢谢
最佳答案
那些表示generics . testfunc<T>(s){ return s; }
意味着 testfunc
接受泛型类型参数 T
. testfunc<boolean>(4)
为该类型参数提供类型参数 ( boolean
)。在该示例中,自 testfunc
以来它没有做任何事情。不使用 T
,但请考虑:
function foo(arg: string) {
let numbers: Array<number> = [];
numbers[0] = arg; // Error: Type 'string' is not assignable to type 'number'.
}
声明 numbers
作为 number
的数组.自 arg
是一个字符串,你不能做 numbers[0] = arg
.
比较:
function foo<T>(arg: T) {
let numbers: Array<T> = [];
numbers[0] = arg; // Error
}
现在,foo
不知道什么numbers
包含,只是它包含的内容将匹配 arg
的类型.所以这两个调用都是有效的:
foo<number>(4);
foo<string>("bar");
为了强调,我在这些调用中包含了类型参数,但 TypeScript 大部分时间都可以推断出它们:
foo(4);
foo("bar");
关于javascript - TypeScript 中像 methodName<string>() 这样的尖括号有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52531416/