你如何在打字稿中声明一个对象数组? [英] how do you declare an array of objects inside typescript?

查看:41
本文介绍了你如何在打字稿中声明一个对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想指定一个将对象数组作为参数的函数,但我没有为该对象定义特定类型(一种匿名类型")

I would like to specify a function that takes an array of objects as a parameter, but I don't have a particular type defined for the object (a sort of "anonymous type")

bagTotal = (products) => {
 // function does stuff
}

我知道我可以做到这一点:

I understand I can do this:

bagTotal = (products: any[]) => {
 // function does stuff
}

但这比我想要的要轻松一些:对打字稿严格.

but this is a bit more relaxed then what I want: to be strict with typescript.

products 是一个外观相同的对象的数组;所有对象都有名称、价格和描述.

products is an array of the same-looking objects; all objects have a name, a price and a description.

我该如何声明?

我想做类似的事情

bagTotal = (products: [{name: string, price: number, description: string}]) => {
 // function does stuff
}

但这不对.我该如何声明?

but that's not right. How can I declare this?

推荐答案

大功告成,只是括号的位置不对:

You're almost there, the placement of the brackets is just wrong:

{name: string, price: number, description: string}[]

您拥有它的方式并非完全错误,但它意味着其他含义:它意味着一个数组,其中仅包含一个此类项目.

The way you had it isn't entirely wrong, but it means something else: it means an array with exactly one item of this type.

我还建议将其提取到界面中,这样可以使类型可重用且更易于阅读:

I'd also recommend extracting it to an interface, it'd make the type reusable and the thing easier to read:

interface Product {
    name: string;
    price: number;
    description: string;
}

const products: Product[];

这篇关于你如何在打字稿中声明一个对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆