代码之家  ›  专栏  ›  技术社区  ›  Jace Johnson

Typescript文件读取的变量类型错误

  •  0
  • Jace Johnson  · 技术社区  · 6 月前

    在我的spec.ts文件中,它为值unitPrice读取了以下错误:“string类型的参数不能分配给number类型的参数。”这是没有意义的,因为在我的.ts文件中,unitPrice是number类型。这些属性应该存储来自我使用springboot创建的api的值,并且unitPrice在我的api中被指定为BigDecimal。所以我不知道从哪里得到unitPrice是一个“字符串类型的参数”。

    这是我的.spec.ts文件:

    import { Product } from './product';
    
    describe('Product', () => {
      it('should create an instance', () => {
        expect(new Product('sku', 'name', 'description', 'unitPrice', 'imageUrl', 'active', 'unitsInStock', 'dateCreated', 'lastUpdated')).toBeTruthy();
      });
    });
    

    这是我的.ts文件

    export class Product {
        constructor(public sku: string,
                    public name: string,
                    public description: string,
                    public unitPrice: number,
                    public imageUrl: string,
                    public active: boolean,
                    public unitsInStock: number,
                    public dateCreated: Date,
                    public lastUpdated: Date
        ) {
            
        }
    }
    

    这是我从api中提取的json代码片段

    "_embedded" : {
        "products" : [ {
          "sku" : "BOOK-TECH-1000",
          "name" : "JavaScript - The Fun Parts",
          "description" : "Learn JavaScript",
          "price" : 19.99,
          "imageUrl" : "assets/images/products/placeholder.png",
          "active" : true,
          "unitsInStock" : 100,
          "dateCreated" : "2024-12-19T14:44:23.000+00:00",
          "lastUpdated" : null,
          "_links" : {
            "self" : {
              "href" : "http://localhost:8080/api/products/1"
            },
            "product" : {
              "href" : "http://localhost:8080/api/products/1"
            },
            "category" : {
              "href" : "http://localhost:8080/api/products/1/category"
            }
          }
        }
    
    1 回复  |  直到 6 月前
        1
  •  2
  •   Naren Murali    6 月前

    如果 unitPrice 类型为number,只需传递一个数值( 1 )而不是字符串( 'unitPrice' ).

    同样的逻辑也适用于 active , dateCreated lastUpdated .

    import { Product } from './product';
    
    describe('Product', () => {
      it('should create an instance', () => {
        expect(new Product('sku', 'name', 'description', 1, 'imageUrl', true, 'unitsInStock', new Date(), new Date())).toBeTruthy();
      });
    });