此代码来自FB ReactNative Movies Demo
function getTextFromScore(score: number): string {
return score > 0 ? score + '%' : 'N/A';
}
什么意思是“:string”,是返回一个字符串?
答案 0 :(得分:2)
此语法适用于flow type checker。在参数列表中,您有(score: number)
,这意味着函数的第一个参数必须是数字。参数列表后是函数的返回值。哪个被声明为字符串。
function getTextFromScore(score: number): string {
return score > 0 ? score + '%' : 'N/A';
}
var x: string = getTextFromScore(5);
Flow很聪明,所以我们可以删除大部分这些注释。
// in no situation will this function not return a string
function getTextFromScore(score: number) {
return score > 0 ? score + '%' : 'N/A';
}
// thus, in no situation will x not be a string
var x = getTextFromScore(5);
我喜欢键入参数并返回函数的值,但通常不是变量,除非我认为它在技术上或可读性方面增加了一些东西。
答案 1 :(得分:0)
这意味着该函数返回一个字符串。
答案 2 :(得分:0)
是的,这意味着此方法将返回一个字符串值.. 如果得分大于0则通过将%与其连接返回值或返回' NA'当值小于或等于0
时答案 3 :(得分:0)
function getTextFromScore(score: number): string {
return score > 0 ? score + '%' : 'N/A';
}
函数获取数字类型的分数并返回字符串
然后
if(score > 0 ){score + '%' }else{'N/A'}