corysimmons
corysimmons

Reputation: 7685

Typescript: How to make an array of objects adhere to an interface?

In the following snippet, Product is a Typescript interface. I would like to ensure every object in products adheres to that interface, but have no idea how. I've tried a few things like products<Product[]>: but nothing seems to work. I'm new to Typescript and would appreciate any help!

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)
    }
  ]
}

Edit:

Simpler example per request

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
    }
  ]
}

Upvotes: 0

Views: 284

Answers (1)

Isolated
Isolated

Reputation: 2453

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);

You can do it like that, alternatively you can just use Product[].

Upvotes: 2

Related Questions