0

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
    }
  ]
}
3
  • Relevant issue is microsoft/TypeScript#13626. Please consider editing the above code to constitute a minimal reproducible example suitable for dropping into a standalone web IDE like The TypeScript Playground so that I can show you a solution/workaround that can be tested. Commented May 15, 2020 at 2:45
  • 1
    Does this work for you? Commented May 15, 2020 at 2:47
  • Yes thank you. I was specifically curious if I could set something like products<Product[]>: {...} inline like that, but it seems I can't. Commented May 15, 2020 at 3:43

1 Answer 1

2
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[].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.