typescript - 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
}
]
}
解决方案
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[]
.
推荐阅读
- angular - Hubspot 表单 - 请求无效 Angular 9
- c++ - 使用 MinGW 编译错误:异常处理
- python-3.x - 使用装饰器时“自我”丢失
- asp.net-mvc - MVC 4 Azure Active Directory 组授权标记
- android-camerax - 如何在单张照片中使用不同的曝光来拍摄照片?
- powershell - GetType().InvokeMember 命令
- javascript - 在reactjs中使用react-bootstrap一次显示两个模态时,如何在第一个模态上方和第二个模态下方显示灰色区域?
- linux - 提升 docker 容器并在其中设置带有命令的新终端
- database - Docker如何管理数据库?
- python - 如何结束线程任务?