let a;
a = 5;
a = "hi";
Why this is valid TypeScript code? Are there any settings to stricter that besides «a:number»? If not, then what's the point of using TypeScipt, if you can use JavaScript + vscode //@ts-check? My tsconfig.json:
"compilerOptions": {
"baseUrl": ".",
"outDir": "build/dist",
"module": "esnext",
"target": "es6",
"lib": ["es6", "dom"],
"sourceMap": true,
"allowJs": false,
"strict": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true
},
3 Answers 3
It works because noImplicitAny does not affect variable declarations. If a variable is declared, but it's type is not declared, it is assumed any.
This was defined like that, because the compiler, despite the variable being any implicitly, can in fact determine its type at every point.
In fact, if you do this:
var a;
a = 5;
a.dot(); // error, number does not have a 'dot' property.
a = "hi";
a.foo(); // error, string does not have a 'foo' property.
You get an error, indicating that string has no property foo, or number has no property dot.
But, if you write:
function(b) {
return b + 2;
}
This function, however, indicates an error because there is nothing that hints the compiler about what type b holds.
3 Comments
any, even i f the variable can take any value of any type. As long as the type can be determined for every line of code in whuch it appears, there won't be an error.Why this is valid TypeScript code?
To allow backwards compability with javascript. This is completely valid js, so it needs to be valid typescript too. But you can easily opt in typechecking:
let a: number;
4 Comments
notImplicitAny turned on. notImplicitAny increases the type safety of your code, but diminishes the compatibility with the existing codebasenotImplicitAny affects function arguments and not variables.Why this is valid TypeScript code?
noImplicityAny only affects "arguments" not "variables".
Consequently this codes is correct:
let a;
a = 'test';
a = 123;
But you will get an error, when you want to declare a functions argument:
function log(someArg) { // Error : someArg has an implicit `any` type
console.log(someArg);
}
This code would work:
function log(someArg: any | string | number) { // Error : someArg has an implicit `any` type
console.log(someArg);
}
TypeScript ensures, that you can use types and validates them, when the variable is in use (eg. as an argument).
Comments
Explore related questions
See similar questions with these tags.
let a: numberstringunderneath, even if it disguised asany