简体   繁体   English

(React-Typescript)如何声明和显示具有未知键数和名称的 object 的泛型类型?

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

I have an object with a field called comments.我有一个 object,其中有一个名为 comments 的字段。 All other fields of different object have the same types.不同 object 的所有其他字段具有相同的类型。 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?我如何 go 为此创建一个类型? And how do I output out both the key and value pairs to display using mui's Typography component?我如何 output 使用 mui 的 Typography 组件显示键和值对? Object.entries? Object.条目? for loop?循环? or map?还是 map? (Preferably using a reusable component, but it's not required) (最好使用可重用的组件,但这不是必需的)

output format example: output 格式示例:

Object A 
taste - okay
price - expensive

Object B
rating - 6.8

Object C
color - silver
model - 2018
status - secondhand

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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