首页 > 解决方案 > Typescript:如何使对象数组遵守接口?

问题描述

在下面的代码片段中,Product是一个 Typescript 接口。我想确保每个对象都products遵守该接口,但不知道如何。我已经尝试了一些东西,products<Product[]>:但似乎没有任何效果。我是 Typescript 的新手,不胜感激!

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

标签: typescripttypescript-generics

解决方案


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


推荐阅读