(React-Typescript) how to declare and display generic type of object with unknown number and name of keys?

Viewed 35

I have an object with a field called comments. All other fields of different object have the same types. The issue is the 'comment' field of different objects are not identical. I don't know the amount, nor the names of the keys of the props that will be passed in, so I cannot use optional fields. I only know that it will be an of type string to any

    //Object A
{
    comment: {taste: "okay", price: "expensive"}
    ...other fields 
    }

    //Object B
{
    comment: {rating: 6.8}
    ...other fields 
    }

    //Object C
{
    comment: {color: "silver", model: 2018, status:"secondhand"}
    ...other fields 
    }

How do i go about creating a type for this? And how do I output out both the key and value pairs to display using mui's Typography component? Object.entries? for loop? or map? (Preferably using a reusable component, but it's not required)

output format example:

Object A 
taste - okay
price - expensive

Object B
rating - 6.8

Object C
color - silver
model - 2018
status - secondhand
1 Answers

You can type up as much as you want / know:

type KnownCommentKeys = 'rating' | 'color' | 'taste' | 'price' | 'model' | 'status'
type YourInnerType = Partial<Record<KnownCommentKeys, string | number>>
type YourType = {
  comment: YourInnerType,
  [key: string]: YourInnerType,
}


//Object A
const a: YourType = {
  comment: {taste: "okay", price: "expensive"}
  //...other fields 
}

//Object B
const b: YourType = {
  comment: {rating: 6.8}
  //...other fields 
}

//Object C
const c: YourType = {
  comment: {color: "silver", model: 2018, status:"secondhand"}
  //...other fields 
}


const d: YourType = {
  comment: {
    
  }
}

const e: YourType = {

}

The answer to second part of this question is:

Object.entries(a).map(([key, value]) => {
  console.log("key:", key, "value:", value)
})
Related