在Typescript中的函数中添加类型

在Typescript中的函数中添加类型,typescript,type-declaration,Typescript,Type Declaration,假设我定义了一个函数: const nonEmpty = (str: string) => str.length > 0; 现在我向nonEmpty添加一个类型,如下所示: const nonEmpty : (str: string) => boolean = (str: string) => str.length > 0; 它可以编译,但我不喜欢参数名(str)出现两次。此外,将参数名称添加到函数类型中没有意义 我更喜欢constnonempty:string

假设我定义了一个函数:

const nonEmpty = (str: string) => str.length > 0;
现在我向
nonEmpty
添加一个类型,如下所示:

const nonEmpty : (str: string) => boolean = (str: string) => str.length > 0;
它可以编译,但我不喜欢参数名(
str
)出现两次。此外,将参数名称添加到函数类型中没有意义

我更喜欢
constnonempty:string=>boolean=…
或类似的。可以用打字脚本吗

另外,我找到了另一种声明函数类型的方法:

 const nonEmpty = (str: string): boolean => str.length > 0;

它看起来更简洁,但对于一个没有经验的Typescript开发人员来说有点奇怪。您喜欢此类型声明吗?

请随意省略第二个
字符串
类型:

const非空:(str:string)=>boolean=(str)=>str.length>0;
nonEmpty('hello')//好的
非空(1)//错误
第二种选择:

type NonEmpty=(a:string)=>boolean
const nonEmpty:nonEmpty=(str)=>str.length>0;

请随意省略第二个
字符串
类型:

const非空:(str:string)=>boolean=(str)=>str.length>0;
nonEmpty('hello')//好的
非空(1)//错误
第二种选择:

type NonEmpty=(a:string)=>boolean
const nonEmpty:nonEmpty=(str)=>str.length>0;

还请注意,typescript可以自动推断类型定义,因此您可能根本不需要显式添加它


还请注意,typescript可以自动推断类型定义,因此您可能根本不需要显式添加它


当然,但我确实想添加类型(并使用“过梁”检查它)当然,但我确实想添加类型(并使用“过梁”检查它)