0

i Would like to know if there is a way to add parameters to a interface of an already created object... Let me explain

I have a Product Class with these properties product.id product.name, now i want to add a quantity property to it... I´m making an sql query that will give me the product object and the quantity and I want to add it to the product interface only to this const so I can do something like console.log(products[0].quantity)

I was tring to do something like this but obviously doesn't work

const products:Array<{...Product, quantity: number}> = (some sql query code with joins xd)

I found a way and is declaring all from scracth but I want to know if there is a better way to do this because this is a little cumbersome specially if the object has more properties

const products:Array<{id: number, name: string, quantity:number}>

Edit: Just found a way but I'm still all ears

const products:Array<Product & {quantity: number}>
1
  • Assuming you can’t modify the original Product type, your method of intersection types is usually what I’d defer to. You could also make a type alias for it if you need it in multiple places. Commented Mar 10, 2021 at 0:14

1 Answer 1

1

Intersection Types

I'm assuming you already have a Product interface i.e.

interface Product {
    foo: string;
    bar: number;
}

You would do it like so

const products = Array<Product & { quantity: number }> = await db.getFromDBExample();

// Example response
console.log(products); // { foo: 'hello', bar: 2, quantity: 3 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.