TypeScript提取在Angular编译器中不按预期工作。

huangapple go评论126阅读模式
英文:

TypeScript Extract not working as expected in Angular compiler

问题

I want to use the TypeScript Extract utility type as a function parameter in an Angular App.

For simplicity, I boiled it down to a minimal working example:

private static doSomething(param: Extract<string | undefined, undefined>): void {}

this.doSomething(undefined);

As I would have expected, the IDE does not show any compile errors. When starting the Angular App, I'm getting a compile error though:

TS2345: Argument of type 'undefined' is not assignable to parameter of type 'never'

The TypeScript version IntelliJ is using is 4.8.4, which is also the version from the package.json, so I assume Angular is using it.
Angular CLI version: 14.2.10, Angular compiler version: 14.2.12

英文:

I want to use the TypeScript Extract utility type as a function parameter in an Angular App.

For simplicity i boiled it down to a minimal working example:

private static doSomething(param: Extract&lt;string | undefined, undefined&gt;): void {}

this.doSomething(undefined);

As i would have expected, the IDE does not show any compile errors. When starting the Angular App i'm getting a compile error though:

TS2345: Argument of type &#39;undefined&#39; is not assignable to parameter of type &#39;never&#39;

The TypeScript version IntelliJ is using is 4.8.4 which is also the version from the package.json, so i assume angular is using it.
Angular CLI version: 14.2.10, Angular compiler version: 14.2.12

答案1

得分: 1

undefined 是一种特殊类型,如果你不启用 strictNullChecks,那么 string | undefined 相当于 stringundefined 可以赋值给 string),所以它提取了 never

如果你仔细考虑,没有启用 strictNullChecks 写这样的代码似乎没有太多意义,它不会让代码更安全。

英文:

undefined is a special type, if you do not enable strictNullChecks then string | undefined is equivalent to string (undefined is assignable to string), so it extracts never.

If you think about it, it makes little sense to write such code without strictNullChecks, it does not make code any safer.

huangapple
  • 本文由 发表于 2023年8月11日 01:10:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76877943.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定