gpt4 book ai didi

javascript - TS 编译 - "noImplicitAny"不起作用

转载 作者:数据小太阳 更新时间:2023-10-29 06:09:51 26 4
gpt4 key购买 nike

我有密码

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

我的 tsconfig.json 是:

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

但是编译成js没有异常是什么鬼?

最好的问候,克罗瓦

最佳答案

因为 z 永远不会被输入为 anyz 的类型只是根据您分配给它的内容进行推断。

来自release notes :

With TypeScript 2.1, instead of just choosing any, TypeScript will infer types based on what you end up assigning later on.

Example:

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

关于javascript - TS 编译 - "noImplicitAny"不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45351563/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com