在我的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服务”或“ng构建”时,我得到多个
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 codegen设置为生成通过严格空检查的文件,或者设置angular cli以在aot编译期间忽略swagger文件的linting?
注意:我必须使用aot编译。
我能想到的唯一解决方案是用程序替换
if (this.configuration.apiKeys["Authorization"])

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

或者objecthasOwnProperty或类似的评估…但这听起来像是暴力策略…

最佳答案

如果实际上总是定义apiKeys,则惯用的typescript解决方案是使用non-null assertion operator
可以使用一个新的!post fix表达式运算符来断言
在类型为
检查者无法断定这一事实。具体来说,手术
null产生一个不包括undefinedx!x类型的值。
所以在你的情况下:

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

也就是说,使用null检查也不是一个坏模式:它是惯用的javascript。
(恐怕我不熟悉招摇过市的codegen,也许其他人可以为您的上游工作流提供有用的答案。)

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

10-10 00:50
查看更多