Red Baron
Red Baron

Reputation: 7642

how do you specify a class function to use typescript props interface

I've just found out I can do:

interface Product {
  name: string,
  price: number,
  category: string,
  id: string,
  quantity: number
}

bagTotal = (products: Product[]) => {

}

which is useful but I have this. where bag is one of my props coming from my redux store

interface IBagProps {
  bag: {
    products: Product[]
  }
}

so in the parameters of the function I want to use the bag props from the IBagProps interface

how do I this?

I wanted to do something like this: bagTotal = (products: IBagProps) => {

but that looks like it's going to pass all the props through

Upvotes: 0

Views: 68

Answers (3)

Karol Majewski
Karol Majewski

Reputation: 25790

You could leverage lookup types:

class Bag extends React.Component<IBagProps> {
  bagTotal = (products: IBagProps['bag']['products']) => {
    /* ... */
  }
}

but it is hardly the most elegant approach. If your method depends on Product[], it is perfectly fine to say:

class Bag extends React.Component<IBagProps> {
  bagTotal = (products: Product[]) => {
    /* ... */
  }
} 

Not only is it more readable, but it also doesn't depend on the shape of your props. If one day you decide to change their structure to, let's say:

interface IBagProps {
  products: Product[]
}

your method signature will not be affected — as it shouldn't be.

Upvotes: 1

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21851

It's as simple as this:

const bagTotal = (products: IBagProps['bag']['products']) => {

}

But normally you just directly use Product[].

UPD, if you probably mean that IBagProps is passed to your function and you have to pull products from there, then destructuring like this can be done:

const bagTotal = ({ bag: {products} }: IBagProps) => {
    products.map(p => p.name)
  }

Upvotes: 1

Walter Barbagallo
Walter Barbagallo

Reputation: 251

You can access to the type of the bag member simply like this:

type BagsInfo = IBagProps['bag']

You can then refactor the bagTotal function to something similar to:

function bagTotal(bagsInfo: BagsInfo) {
  return bagsInfo.products.length
}

If your bagTotal function is directly "connected" to the products array you can retrieve the Product type with:

type Product = IBagProps['bags']['products'][number]

Upvotes: 1

Related Questions