【问题标题】:TS2322: Type 'Todo[] | null' is not assignable to type 'Todo[]'. Type 'null' is not assignable to type 'Todo[]'TS2322:类型“待办事项 [] | null' 不能分配给类型 'Todo[]'。类型“null”不可分配给类型“Todo[]”
【发布时间】:2021-02-16 01:36:37
【问题描述】:

关于下面的代码,我有两个问题。我遇到的问题会在我遇到问题的代码行之后进行注释。

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

谢谢,

【问题讨论】:

  • 这行得通吗? .subscribe(todos => this.todos = todos.body ?? []);
  • 它有效。谢谢!

标签: angular typescript declaration


【解决方案1】:

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

如果你不想分配一个空数组并且你确定它会被初始化,你可以使用 Non-Null Assertion Operator:

todos!: Todo[];

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

todos?: Todo[];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2021-06-08
    • 2021-06-12
    相关资源
    最近更新 更多