typescript - Angular 5 + Swagger Codegen && 严格空检查

标签 typescript angular-cli swagger-codegen

在我的 angular-cli(最新)项目(ng v5 LTS)的 tsconfig.json 中,我已经设置(并且必须保留它)

"strictNullChecks": true,

我使用 Swagger Codegen (Maven v2.3.1) 生成 api 客户端模型。该命令正在使用这些选项:

`-jar ${jarPath} generate -i ${apiPath} -l typescript-angular -o ${outputPath} --type-mappings Date=string -D withInterfaces=true --additional-properties ngVersion=5`

在 .angular-cli.json 中,我将生成的文件从 linting 中排除,例如:

  ...,
  "lint": [
    {
      ...
      "exclude": ["**/swagger/**"]
    }, ...

当我执行“ng serve”或“ng build”时,我得到多个

error TS2532: Object is possibly 'undefined'

用于生成的配置对象。就像这个:

...
import { Configuration } from '../configuration';
...
if (this.configuration.apiKeys["Authorization"]) {
    headers = headers.set('Authorization',
    this.configuration.apiKeys["Authorization"]);
}
...

我也尝试在 tslint.json 和 tsconfig 扩展中排除生成的 swagger 文件,但没有成功。

有没有办法将 Swagger Codegen 设置为生成通过严格空检查的文件,或者将 Angular CLI 设置为在 aot 编译期间忽略 swagger 文件?

注意:我必须使用 AOT 编译。


我能想到的唯一解决方案是以编程方式替换所有实例

if (this.configuration.apiKeys["Authorization"])

if (this.configuration.apiKeys && this.configuration.apiKeys["Authorization"])

或 objectHasOwnProperty 或类似的评估...但这听起来像是一种蛮力策略...

最佳答案

如果 apiKeys 实际上是 always 定义的惯用 TypeScript 解决方案是使用 non-null assertion operator ,

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded.

所以在你的情况下:

if (this.configuration.!apiKeys["Authorization"]) { ... }

也就是说,使用 .hasOwnProperty() 检查也不是一个坏模式:它是惯用的 JavaScript。

(恐怕我不熟悉 Swagger Codegen,也许其他人可以为您的上游工作流提供有用的答案。)

关于typescript - Angular 5 + Swagger Codegen && 严格空检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51599920/

相关文章:

java - 来自现有 JSON 的 Springfox Swagger Ui

jqgrid - TypeScript 和 jqGrid

angular - 如何在 Angular 6+ CLI 中使用 Handlebars.js?

angular - ng build --prod 无法确定 X 类的模块!将 ThreadListTabsComponent 添加到 NgModule 以修复它

java - 如何使用多个 yaml 文件生成 openAPI 代码

swagger - 如何合并多个 OpenAPI 规范?

javascript - NestJS WebSocketGateway 未初始化

javascript - typescript 中的 `export type` 是什么?

typescript - 为什么函数类型的参数不能接受其参数实现原始参数接口(interface)的参数?

angular - ng build --prod 抛出异常