如何解决错误 TS2322: undefined' 不能分配给类型 'Product'
这是我的 service.ts 文件,其中 getProductById 方法所属并给出错误。
import { Inject,Injectable } from '@angular/core';
import { inject } from '@angular/core/testing';
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor() { }
getProducts(): Product[] {
return products.map(p =>new Product(p.id,p.title,p.price,p.rating,p.description,p.categories));
}
getProductById(productId: number): Product{
return products.find(p => p.id === productId);
}
}
export class Product{
constructor(
public id: number,public title: string,public price: number,public rating: number,public description: string,public categories: string[]){}
}
export class Review {
constructor(
public id: number,public productId: number,public timestamp: Date,public user: string,public comment: string) {
}
}
const products =[
{
'id': 0,'title': 'First product','price': 24.99,'rating': 4.3,'description': 'This is a short description for product Zeroth','categories': ['electronics','hardware']
},{
'id': 1,'title': 'Second Product','price': 64.99,'rating': 3.5,'description': 'This is a short description. Lorem ipsum dolor sit amet,consectetur adipiscing elit.','categories': ['books']
},{
'id': 2,'title': 'Third Product','price': 74.99,'rating': 4.2,'categories': ['electronics']
},{
'id': 3,'title': 'Fourth Product','price': 84.99,'rating': 3.9,'categories': ['hardware']
},{
'id': 4,'title': 'Fifth Product','price': 94.99,'rating': 5,{
'id': 5,'title': 'Sixth Product','price': 54.99,'rating': 4.6,'categories': ['books']
}
]
这个是 product-detail.component 我想通过 Id 获取详细信息
import { Component,OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Product,ProductService} from '../shared/product.service';
@Component({
selector: 'nga-product-detail',templateUrl: './product-detail.component.html',styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {
public product!: Product;
constructor(private route: ActivatedRoute,private productService: ProductService) { }
ngOnInit(): void {
const prodId: number = parseInt(this.route.snapshot.params['productId']);
this.product = this.productService.getProductById(prodId);
}
}
错误信息:-
错误:src/app/shared/product.service.ts:16:5 - 错误 TS2322:类型 '{ id: number;标题:字符串;价格:数量;评级:数量;描述:字符串;类别:字符串[]; } | undefined' 不能分配给类型 'Product'。 “未定义”类型不能分配给“产品”类型。
16 return products.find(p => p.id === productId);
解决方法
您必须在 getProductById()
上使用与 Array.find()
相同的签名,因为如果没有,您就告诉 TS 您的函数应该只返回 Product
值,但它也可以像 undefined
一样返回 find()
。因此,请完成您的功能,例如:
getProductById(productId: number): Product | undefined {
return products.find(p => p.id === productId);
}
或者简单地删除返回类型并让 TS 推断它:
getProductById(productId: number): {
return products.find(p => p.id === productId);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。