Adding type in a function in Typescript

613 views Asked by At

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 ?

2

There are 2 answers

0
captain-yossarian from Ukraine On

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;
1
Hoff On

Also note that typescript can automatically infer the type definition, so you might not need to explicitly add it at all.

enter image description here