typescript 你如何在打字稿中声明一个对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53964694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:45:17  来源:igfitidea点击:

how do you declare an array of objects inside typescript?

javascriptreactjstypescript

提问by Red Baron

I would like to specify that function takes array of objects as parameter, but I don't have particular type defined for the object (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 my typescript.

但这比我想要的要轻松一些:严格遵守我的打字稿。

productsis an array of same-looking objects like all objects have name, price, description.

products是一组外观相同的对象,就像所有对象都有名称、价格、描述。

how can I declare that?

我怎么能声明呢?

I want to do something like

我想做类似的事情

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

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

但这是不对的。我该如何声明?

回答by Ingo Bürk

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

回答by bautigaraventa

I think you must declare the class "Product" so you can declare a Product array like this:

我认为您必须声明“Product”类,以便您可以像这样声明一个 Product 数组:

products: Product[];

and pass it as a parameter like this:

并将其作为参数传递,如下所示:

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

To have the class you can do a new .ts file with this code:

要拥有该课程,您可以使用以下代码创建一个新的 .ts 文件:

export class Product {
  name: String;
  price: Number;
  description: String;
}

I wish that helped!

我希望这有帮助!

Thank you.

谢谢你。

回答by Sockness_Rogers

If you are declaring an array of a specific object and want to specify type for variables in the objects, I would create a class for the object like this:

如果您要声明特定对象的数组并希望为对象中的变量指定类型,我会为该对象创建一个类,如下所示:

class Item(){
    name: string;
    description: string;
    etc: any

  constructor() {
    this.name;
    this.description;
    this.etc;
}}

Then you can specify the array as an array of item objects:

然后,您可以将数组指定为项对象数组:

itemArray: Array<Item>;