gpt4 book ai didi

typescript - TypeScript 可以警告我关于非空断言运算符的过度使用吗?

转载 作者:搜寻专家 更新时间:2023-10-30 20:34:19 41 4
gpt4 key购买 nike

考虑以下 TypeScript 代码:

let x = { foo: { bar: "baz" } };
console.log(x.foo!.bar);

在这里,x.foo 的推断类型是{ bar: string } , 因此不需要使用非空断言运算符 ! (参见例如 https://github.com/Microsoft/TypeScript/issues/7395 ):编译器已经知道 x.foo不能为空。

tsc(或者可能是广泛使用的第三方工具,如 TSLint)能否警告我这些多余的 ! 用途? ,和/或这是计划中的功能吗?

我确信这在原则上是可行的(似乎这只是使用 TypeScript 编译器 API 来识别 ! 用于类型不是 T | nullT | undefined 的变量的地方的问题);我只是想知道繁重的工作是否已经完成。或者,我猜,指向 TypeScript 编译器 API 相关部分的指针也可以工作 - 很难找到它的文档(我猜是因为它还不稳定)。

(我问的原因是我担心我最终将不得不处理代码,其中过去一些白痴到处洒!以使tsc --strictNullChecks停止发出错误,而没有真正考虑断言变量在运行时是否 为非 null。如果它在运行时确实以 null 结束,瞧!我们本可以在编译时捕获的错误,但不是因为过分热心 ! 。在已知为非空的变量上存在 ! 会强烈暗示代码过度使用了 ! ,很可能是错误的。)

最佳答案

TSLint 现在通过 no-unnecessary-type-assertion rule 执行此操作.

代码如下:

const x: string = "foo";
const y = x!.indexOf("f"); // <-- x is of type string; no need to assert non-null

会触发类似这样的警告:

This assertion is unnecessary since it does not change the type of the expression.

关于typescript - TypeScript 可以警告我关于非空断言运算符的过度使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41453570/

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