How to force TypeScript to ensure that all const, let & var variables must be declared with their types

1.1k Views Asked by At

I have just installed TypeScript, having come from a Pascal / Java background and expected the following snippet to fail to be compiled for two reasons (line 2 - message used before it is defined, line 4 - Type boolean is not assignable to type string)

I was expecting TypeScript to raise an exception at line 1 - 'Variable defined without specifying Type'.

let message;
console.log(message);
message = "Hello this other world";
message = false;
console.log(message);

In order that TypeScript should do its job I have to amend the first line to

let message: string;

The two exceptions (line 2, line 4) now both get highlighted as expected.

My tsconfig.json is defined as

{
  "compilerOptions": {
    "target": "es2020",
    "strict": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "module": "commonjs",
    "outDir": "javaScript",
    "sourceMap": true
  }
}

Am I missing an attribute within the tsconfig.json file that would enable this feature or do I have to just accept that I have to remember to provide TypeScript with the data type each time I use const, let or var

Interestingly, the functionality appears to be as expected when declaring functions. For example

const addOne = (i: number): number => i + 1;
const addOneEquals = (addOne(4) === false);

If you remove the :number function return type, the comparison still flags up as an exception types number and boolean have no overlap. This is due to TypeScript being able to deduce the type from the function body and so is still safe even if I forget to define the return type, although I would prefer TypeScript to force this for me.

If you remove the : number from the parameter, TypeScript flags up the exception at (i) of Parameter 'i' implicitly has an 'any' type.

Therefore, in conclusion, why doesn't let message; flag the same exception - i.e. Variable 'i' implicitly has an 'any' type. Unlike functions, TypeScript can't defer the type from the simple let statement and so I would expect an exception as it is unsafe to continue without knowing.

0

There are 0 best solutions below