You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Typescript:如何声明键未知的泛型对象并展示其键值对?

解决方案:类型定义与MUI可复用组件实现

一、TypeScript类型定义

因为comment字段是字符串键对应任意类型值的不确定结构,我们可以用Record<string, unknown>精准描述它,再结合固定字段的基础类型:

// 定义所有对象共有的固定字段
type BaseItem = {
  name: string; // 对应示例中的"Object A/B/C"标识
  // 这里添加其他固定字段,比如id、createTime等
};

// 组合固定字段与动态comment字段的最终类型
type Item = BaseItem & {
  comment: Record<string, unknown>;
};

Record<string, unknown>完美适配需求:键必须是字符串类型,值可以是任意类型,完全兼容你示例中不同结构的comment。

二、MUI可复用组件实现

我们可以封装一个专门渲染comment键值对的组件,利用Object.entries遍历comment对象,结合MUI的Typography和Box组件实现排版:

import React from 'react';
import { Typography, Box } from '@mui/material';
import { Item } from './types'; // 导入上面定义的类型

// 组件props类型
interface CommentDisplayProps {
  item: Item;
}

const CommentDisplay: React.FC<CommentDisplayProps> = ({ item }) => {
  return (
    <Box sx={{ marginBottom: 3 }}>
      {/* 渲染对象名称(如Object A) */}
      <Typography variant="h6" fontWeight="bold">
        {item.name}
      </Typography>
      {/* 遍历comment的键值对并渲染 */}
      {Object.entries(item.comment).map(([key, value]) => (
        <Typography 
          key={key} 
          variant="body1" 
          sx={{ marginLeft: 2, marginTop: 0.5 }}
        >
          {key} - {String(value)}
        </Typography>
      ))}
    </Box>
  );
};

export default CommentDisplay;

使用组件

当你有一批对象数组时,直接循环渲染即可:

import CommentDisplay from './CommentDisplay';

const items: Item[] = [
  {
    name: 'Object A',
    comment: { taste: 'okay', price: 'expensive' },
    // 其他固定字段...
  },
  {
    name: 'Object B',
    comment: { rating: 6.8 },
    // 其他固定字段...
  },
  {
    name: 'Object C',
    comment: { color: 'silver', model: 2018, status: 'secondhand' },
    // 其他固定字段...
  },
];

const App = () => {
  return (
    <Box sx={{ padding: 3 }}>
      {items.map(item => (
        <CommentDisplay key={item.name} item={item} />
      ))}
    </Box>
  );
};

export default App;

这样就能得到你期望的输出格式,组件完全可复用,无论comment的结构如何变化都能适配。


内容的提问来源于stack exchange,提问作者xorbet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:09:30