Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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".

like image 808
Michelle Avatar asked Feb 07 '14 19:02

Michelle


People also ask

How do you assign a type to a variable in TypeScript?

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable.

Does TypeScript enforce types?

Bookmark this question.

Should you type everything in TypeScript?

Yes, you should make it a habit to explicitly set all types, it's will prevent having unexpected values and also good for readability.

Is it bad practice to use any in TypeScript?

any. ❌ Don't use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.


2 Answers

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>.

like image 75
WiredPrairie Avatar answered Oct 07 '22 01:10

WiredPrairie


You could also set in your tsconfig.json:

{   "compilerOptions": {      "noImplicitReturns": true,      "noImplicitAny": true   } } 
like image 42
Daniel Kucal Avatar answered Oct 07 '22 00:10

Daniel Kucal