TS2322:类型 'Todo[] | null' 不可分配给类型 'Todo[]'。类型 'null' 不可分配给类型 'Todo[]'

TS2322: Type 'Todo[] | null' is not assignable to type 'Todo[]'. Type 'null' is not assignable to type 'Todo[]'

关于下面的代码,我有两个问题。我的问题在我遇到问题的代码行之后进行了评论。

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { tap } from 'rxjs/operators';

interface Todo{
  id: number,
  content: string;
  completed: boolean;
}

@Component({
  selector: 'app-root',
  template: `
    <ul>
      <li *ngFor="let todo of todos">{{ todo.content }}</li>
    </ul>
    <pre>{{ todos | json }}</pre>
  `,
  styles: []
})
export class AppComponent implements OnInit{
  todos: Todo[] = []; //Why do I need to initialize it everytime? when I tried to just declare the variable, it throws an error.
  url = 'http://localhost:3000/todos';

  constructor(public http: HttpClient){}

  ngOnInit(){
    this.http.get<Todo[]>(this.url, {observe: 'response'})
    .pipe(
      tap(res => console.log(res)),
      tap(res => console.log(res.headers)),
      tap(res => console.log(res.status))
    )
    .subscribe(todos => this.todos = todos.body);**//TS2322**: Type 'Todo[] | null' is not assignable to type 'Todo[]'.Type 'null' is not assignable to type 'Todo[]'.
  }

}
  1. 为什么我不能只在 Angular 中声明一个变量?为什么我应该总是用一个空值初始化它来绕过错误?
  2. 如何修复错误 'ts2322'?这个错误的原因是什么?

谢谢,

这是因为您在 tsconfig.json 中启用了 Strict Property Initialization(或严格)。 有了这个,你必须直接或在构造函数中设置所有 属性。

如果你不想用一个空数组赋值,并且你确定它会被初始化,你可以使用非空断言运算符:

todos!: Todo[];

或者您需要将其设为可选:

todos?: Todo[];