How do I translate this map function from Javascript to Typescript given the structure of the data object being mapped?

Viewed 18

I'm translating an app from Javascript to Typescript and I have come upon a type declaration situation I do not know how to resolve. I barely understand how I got this to work to begin with in JS:

{data.listing.map(({ token: { name, display_uri }, price, amount_left }, index, arr) => (
          <Col key={index} id={index} xs={4} sm={4} md={3} lg={2}>
            {display_uri ? <StateImg src={"https://ipfs.io/ipfs/" + display_uri.slice(7,)}/>: null}
            <h5>name: {name}</h5>
            <p>price: {price / 1000000}</p>
            <Row>
              <QuantityForm
              value={batch.find((b) => b.index === index)?.count || 0}
              maxValue={amount_left}
              onChange={(v) => onChange(index, v, arr[index], target)}
            />
            </Row>
          </Col>
        ))}

How do I format the param declarations correctly given the following types:

name = string,
display_uri = string,
price = number,
amount_left = number,
index = number,
arr = Object[] (not sure if this one is correct; it's the 3rd map param, so it's the same array being mapped)

Kind thanks for any help. It is greatly appreciated.

1 Answers

You're better off defining the type of data, but without further code or context, you can use as to cast data.listing to the correct type:

(data.listing as {
    token: { name: string; display_uri: string; };
    price: number;
    amount_left: number;
}[]).map(({ token: { name, display_uri }, price, amount_left }, index, arr) =>

You might want to try the official TypeScript handbook before using TypeScript to get a feel for it.

Related