简体   繁体   中英

How to force all variables in Typescript to have a type declared

I understand that when you declare a variable in Typescript, you can choose whether or not to specify a type for the variable. If no type is specified, the default "any" type is used. Is there a way to force all variables to have a type declared, even if it may be "any". As in, I want a compiler error when a type isn't specified. This is so that programmers would be forced to give everything a type and prevent cases where variables are accidentally left as "any".

It's not true that a variable declared is necessarily without type in TypeScript. The TypeScript compiler will, when possible, infer a type based on the right hand side of a declaration.

For example:

var x = 150;

x will be a Number as the RHS is a number.

You can use the command line compile option to catch declarations where the type cannot be inferred by using --noImplicitAny :

Warn on expressions and declarations with an implied 'any' type.

This option would catch a case where a variable d for example is declared, yet not assigned to a value immediately.

var d;

Will produce an error:

error TS7006: Parameter 'd' of 'test' implicitly has an 'any' type.

The compiler switch also catches parameters without a specified type, and as @basarat pointed out in a comment, it also catches return types and class/interface members.

There's a little more information in this blog post as well. Note that there's also an equivalent MSBuild/project setting available: <TypeScriptNoImplicitAny> .

You could also set in your tsconfig.json :

{
  "compilerOptions": {
     "noImplicitReturns": true,
     "noImplicitAny": true
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM