简体   繁体   中英

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

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]

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)
  }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM