Angular16类型不匹配基础问题?-灵析社区

MastFancy

这个 `undefined`,是哪里出了问题?感觉很简单,又解决不了。 ![](https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20250103/8ad90103ed48240afe3f0d0c210328f4.png) 1.todo.service.ts import { Injectable } from '@angular/core'; import { Todo } from '../interface'; @Injectable({ providedIn: 'root' }) export class TodoService { private data: Todo[] = [ {id: 10, description: "For test purpose", category: 1, content: 'test1'}, {id: 12, description: "For test2 ", category: 1, content: 'test2'}, {id: 15, description: "For test3 ", category: 1, content: 'test3'} ] getTodo(id: number): Todo { return this.data.find(item => item.id ===id) } 2. interface export interface Todo { id: number; description: string; category: number; content: string; } export enum Category { html, css, js } 3. details export class DetailComponent implements OnInit{ todo!: Todo; constructor(private route: ActivatedRoute, private todoServe: TodoService) {} ngOnInit(): void { const id = Number(this.route.snapshot.paramMap.get('id')) this.todo = this.todoServe.getTodo(id) } }

阅读量:18

点赞量:0

问AI
六股小子
如果你能确保 id 一定在数组中找得到的话 直接采用(!)非空断言即可。 getTodo(id: number): Todo { return this.data.find(item => item.id ===id)! }