我有代码
let z;
z = 50;
z = 'z';
我的tsconfig.json是:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"sourceMap": false,
"noEmitOnError": true,
"strict": true,
"noImplicitAny": true
}
}
但是到底有什么例外可以编译到js?
最诚挚的问候, Crova
答案 0 :(得分:5)
因为永远不会将z
输入为any
。 z
的类型只是根据您分配给它的内容推断出来。
使用TypeScript 2.1,而不是只选择任何,TypeScript将 根据您最后分配的内容推断类型。
示例:强>
let x; // You can still assign anything you want to 'x'. x = () => 42; // After that last assignment, TypeScript 2.1 knows that 'x' has type '() => number'. let y = x(); // Thanks to that, it will now tell you that you can't add a number to a function! console.log(x + y); // ~~~~~ // Error! Operator '+' cannot be applied to types '() => number' and 'number'. // TypeScript still allows you to assign anything you want to 'x'. x = "Hello world!"; // But now it also knows that 'x' is a 'string'! x.toLowerCase();
所以在你的情况下:
let z;
z = 50;
let y = z * 10; // `z` is number here. No error
z = 'z';
z.replace("z", "")// `z` is string here. No error
答案 1 :(得分:1)
noImplicitAny
字面意思是:
如果TypeScript使用'任何'触发错误无论何时它无法推断a 型
在上面的例子中,代码编译器的任何一点都可以轻松推断出z
的类型。因此,它可以检查您是否允许在z
上调用适当的方法/道具。