Reputation: 42100
Suppose I define a function:
const nonEmpty = (str: string) => str.length > 0;
Now I'm adding a type to nonEmpty
like that:
const nonEmpty : (str: string) => boolean = (str: string) => str.length > 0;
It compiles but I don't like that the argument name (str
) appears twice. Moreover, the argument name does not make sense to add an argument name to the function type.
I would prefer const nonEmpty : string => boolean = ...
or similar. Is it possible in Typescript ?
P.S. I found another way to declare a function type:
const nonEmpty = (str: string): boolean => str.length > 0;
It looks more concise but a bit strange for an inexperienced Typescript developer. Would you prefer this type declaration ?
Upvotes: 0
Views: 624
Reputation: 39896
Also note that typescript can automatically infer the type definition, so you might not need to explicitly add it at all.
Upvotes: 1
Reputation: 33101
Feel free to omit second string
type:
const nonEmpty : (str: string) => boolean = (str) => str.length > 0;
nonEmpty('hello') // ok
nonEmpty(1) // error
Second option:
type NonEmpty = (a: string) => boolean
const nonEmpty: NonEmpty = (str) => str.length > 0;
Upvotes: 1