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

时间:2021-02-16 01:36:37

标签: angular typescript declaration

我对下面的代码有两个问题。在我遇到问题的代码行之后对我提出的问题进行了评论。

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”?此错误的原因是什么?

谢谢,

1 个答案:

答案 0 :(得分:0)

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

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

todos!: Todo[];

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

todos?: Todo[];