【问题标题】:Angular 11 any/undefined types warningsAngular 11 任何/未定义类型警告
【发布时间】:2021-03-08 02:58:28
【问题描述】:

我将我的应用从 Angular v10 升级到 v11,现在我收到多个错误和警告,因为某些(可能是所有)字段可能一次未定义:

例如:

const savedToken = new Token(JSON.parse(localStorage.getItem(AuthInterceptor.tokenKey)));

必须变成:

const savedToken = new Token(JSON.parse(<string>localStorage.getItem(AuthInterceptor.tokenKey)));

警告:

Argument of type 'string | null' is not assignable to parameter of type 'string'. 
Type 'null' is not assignable to type 'string' 
// I know the localStorage value can be null in this case.

另一个例子:

public user$: Observable<User>;
// Property 'user$' has no initializer and is not definitely assigned in the constructor.

因为user$ngOnInit() 中被初始化为this.user$ = this.store.pipe()...

你是怎么解决的?

即使我从angular.json 停用strict,结果也是一样的:

"@schematics/angular:application": {
    "strict": false
}

我真的需要将我所有的应用程序代码逐行更新为 angular 11?谢谢

【问题讨论】:

    标签: angular typescript strict


    【解决方案1】:

    这是由 TypeScript 的严格类初始化引起的。

    https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#strict-class-initialization

    解决方案 1

    利用 TypeScript 文档中指示的 prop!: Type 语法向编译器表明我们知道该道具尚未初始化,我们将在稍后处理它。

    @Component({...})
    export class ExampleComponent {
     @Input() inputExampleProp!: string; // ! indicates that we know the variable may be undefined
    }
    

    替代解决方案

    如果您不关心严格的类初始化,您可以在您的 tsconfig.json 中通过在编译器选项中添加一个标志来完全禁用该功能

    {
     "compilerOptions": {
        "strictPropertyInitialization": false
      }
    }
    

    注意:您可能需要重新启动 IDE 才能刷新 compilerOptions。

    【讨论】:

    • 感谢您的回答。使用 strictPropertyInitialization: false 仍然无法正常工作(即使重新启动 IDE)。我需要使用 prop!: 每个声明的类型。即使在我使用表单字段的地方,我也需要使用“?”检查它是否存在: const username = this.registerForm.get('userName')?.value;
    • 替代解决方案解决我的生活。提示:在“compilerOptions”上,而不是在“AngularComiplerOptions”上
    • 你不必重启 WebStorm 就能注意到 tsconfig.json 的变化
    • 感谢您的回答,第二个解决方案对我不起作用,第一个解决方案是的
    猜你喜欢
    • 2020-12-18
    • 2021-04-29
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多