selanac82
selanac82

Reputation: 3000

Enforce explicit function return type annotations?

I want to disable the ability to use "any" in typescript. For example, I have the following function

func() {
   return true
}

i want to require it to be this

func(): boolean {
    return true
}

I know TSLint can check for this, but I can ignore it and still compile. Is there anyway to require this in order to compile in the TSConfig file?

Upvotes: 15

Views: 13938

Answers (1)

Avin Kavish
Avin Kavish

Reputation: 8947

No, Function return types are inferred in typescript. The compiler itself has no setting to turn off type inference on functions. This feature was requested and decline as discussed in this issue filed on the typescript repository.

However, your favourite lint tool can warn you when there is no type definition specified for a function. For completeness, I will provide this information.

tslint (deprecated)

The rule is called typedef. Add the following line to your tslint config

"typedef": [ true, "call-signature", "arrow-call-signature" ]

typescript-eslint

The typescript-eslint plugin has this rule called explicit-function-return-type.

  "rules": {
    "@typescript-eslint/explicit-function-return-type": "error"
  }

Upvotes: 20

Related Questions