Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

javascript - how do you declare an array of objects inside typescript?

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 is an array of the same-looking objects; all objects have a name, a price and a description.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...