Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...