【问题标题】:How to fix "TodoItem undefined is not assignable to type TodoItem" error?如何修复“TodoItem undefined is notassignable to type TodoItem”错误?
【发布时间】:2021-09-02 22:31:44
【问题描述】:

我正在学习 TypeScript。

todoItem.ts的内容:

export class TodoItem {
  constructor(
    public id: number,
    public task: string,
    public complete: boolean = false
  ) {}

  printDetails(): void {
    console.log(
      `${this.id}\t${this.task} ${this.complete ? "\t(complete)" : ""}`
    );
  }
}

todoCollection.ts的内容:

import { TodoItem } from "./todoItem";

export class TodoCollection {
  private nextId: number = 1;

  constructor(public userName: string, public todoItems: TodoItem[] = []) {}

  addTodo(task: string): number {
    while (this.getTodoById(this.nextId)) {
      this.nextId++;
    }
    this.todoItems.push(new TodoItem(this.nextId, task));
    return this.nextId;
  }

  getTodoById(id: number): TodoItem {
    return this.todoItems.find((item) => item.id === id);
  }
}

使用tsc 编译时,出现以下错误:

src/todoCollection.ts:17:5 - 错误 TS2322:类型 'TodoItem |不明确的' 不可分配给类型“TodoItem”。类型“未定义”不是 可分配给类型“TodoItem”。

17 return this.todoItems.find((item) => item.id === id); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~

发现 1 个错误。

问题

如何解决这个错误?我真的不知道,因为我无法发现任何特殊性。一切看起来都很好。

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    如果谓词函数没有为数组的任何元素返回真值,Array#find 可能会返回 undefined。 Typescript 抱怨,因为您告诉它您将在方法标头中返回 TodoItem,但您实际上试图返回可能是 TodoItemundefined 的东西(就静态分析而言) )。

    您有几种解决方法:

    1. | undefined 添加到您的返回类型,例如
    getTodoById(id: number): TodoItem | undefined {
    
    1. 在未找到项目时添加一些其他流控制,例如抛出异常
    getTodoById(id: number): TodoItem {
      const result = this.todoItems.find(item => item.id === id)
      if (!result) {
        throw new Error("Not Found!");
      }
      return result;
    }
    
    1. 使用非空断言运算符。如果您知道这总是会找到结果,您可以简单地告诉 TS,通过使用! 后缀运算符,返回值永远不会为 null 或 undefind。
    return this.todoItems.find(item => item.id === id)!
    
    1. 在您的 ts 配置中禁用严格的空检查。我不推荐这个选项,但是可以通过在 tsconfig.json 中配置选项来尽可能少地或尽可能多地使用 typescript。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2016-01-14
    • 2022-12-07
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多