2017-07-27 40 views
4

我的代碼TS彙編 - 「noImplicitAny」不工作

let z; 
z = 50; 
z = 'z'; 

和我tsconfig.json是:

{ 
    "compilerOptions": { 
    "target": "es5", 
    "module": "commonjs", 
    "sourceMap": false, 
    "noEmitOnError": true, 
    "strict": true, 
    "noImplicitAny": true 
    } 
} 

但是,什麼是地獄它是有throgh編譯沒有異常js?

最好的問候, Crova

回答

1

noImplicitAny的字面意思是:

觸發如果打字稿使用錯誤 '任何' 時,它不能推斷 型

你的情況以上在你的代碼編譯器的任何一點都可以很容易地推斷出z的類型。因此它可以檢查是否允許您撥打z的適當方法/道具。

4

因爲z從未輸入爲anyz的類型根據您分配的內容簡單推斷出來。

release notes

隨着打字稿2.1,而不是隻選擇任何,打字稿會根據你最終後來分配 推斷類型。

例子:

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 
+0

是否有禁止此行爲的標誌? – user7353781

+0

沒有據我所知。 – Saravana