英文:
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<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
答案1
得分: 1
undefined 是一种特殊类型,如果你不启用 strictNullChecks,那么 string | undefined 相当于 string(undefined 可以赋值给 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论