TypeScript测试报错:string参数无法赋值给number类型的unitPrice
问题分析与解决
一、测试用例类型不匹配报错
你在spec.ts的测试代码里,创建Product实例时给unitPrice传的是字符串'unitPrice',但Product类构造函数中unitPrice定义为number类型,TypeScript因此抛出类型不匹配错误。不仅是unitPrice,active(传了字符串'active',需布尔值)、unitsInStock(传了字符串'unitsInStock',需数字)、dateCreated和lastUpdated(传了字符串,需Date对象)的参数类型都不符合要求,这是测试用例的参数写错了,和API返回的BigDecimal类型无关。
修正后的测试用例示例:
import { Product } from './product'; describe('Product', () => { it('should create an instance', () => { expect(new Product( 'TEST-SKU', 'Test Product', 'A test product description', 29.99, // 传入数字类型的unitPrice '/assets/test-image.png', true, // 传入布尔值active 30, // 传入数字类型unitsInStock new Date('2024-12-19'), // 传入Date对象 new Date('2024-12-19') )).toBeTruthy(); }); });
二、API字段与类属性不匹配问题
API返回的价格字段是price,但你的Product类中对应的属性是unitPrice,这会导致数据自动映射时无法正确赋值。可以通过以下两种方式解决:
- 修改类属性名:把Product类中的
unitPrice改为price,和API返回字段保持一致,这样自动映射就能正常工作; - 手动处理字段映射:如果不想修改类属性名,在请求API后处理响应数据时,手动将
price字段的值赋值给unitPrice,同时注意把日期字符串转为Date对象:
// 示例:用axios请求API并处理数据 axios.get('/api/products') .then(res => { const productList = res.data._embedded.products.map(item => { return new Product( item.sku, item.name, item.description, item.price, // 将API的price赋值给类的unitPrice item.imageUrl, item.active, item.unitsInStock, new Date(item.dateCreated), item.lastUpdated ? new Date(item.lastUpdated) : null ); }); });
内容的提问来源于stack exchange,提问作者Jace Johnson
相关产品推荐
相关产品推荐

