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
},
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.
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;
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).
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.