代码之家  ›  专栏  ›  技术社区  ›  corysimmons

如何使一个对象数组附着到一个接口上?

  •  0
  • corysimmons  · 技术社区  · 6 年前

    在下面的片段中, Product products 坚持那个界面,但不知道怎么做。我试过一些类似的事情 products<Product[]>: 但似乎什么都不管用。我是打字新手,希望你能帮我!

    import * as faker from 'faker'
    import { v4 as uuidv4 } from 'uuid'
    
    import { Product } from './models/Product'
    
    export default {
      products: [
        {
          id: uuidv4(),
          name: faker.commerce.product(),
          description: faker.random.words(7),
          cents: faker.commerce.price(300, 15000),
          quantity: faker.random.number(15)
        }
      ]
    }
    

    编辑:

    每个请求的简单示例

    interface Product {
      id: string
      name: string
      quantity: string
    }
    
    export default {
      products: [ // How to make sure all objects in this array adhere to the Product interface above?
        {
          id: 1,
          name: 'Banana',
          quantity: 10
        }
      ]
    }
    
    0 回复  |  直到 6 年前
        1
  •  2
  •   Isolated    6 年前
    interface Product {
        id: string;
        name: string;
        description: string;
        cents: number;
        quantity: number;
    }
    
    interface ProductCollection {
        products: Product[];
    }
    
    const collection: ProductCollection = {
        products: [
            {
                id: '1',
                name: 'something',
                description: 'An example',
                cents: 10,
                quantity: 1
            }
        ]
    }
    
    console.log(collection);
    

    你可以这样做,或者你可以用 Product[]

    推荐文章