0

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 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Sure but I do want to add the type (and use a "linter" to check it)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.