首页 > 解决方案 > Typescript 接口不接受带有强制键的动态对象

问题描述

我需要为它作为道具传递的这个对象数组使用一个接口。

const playersData = [
    {
        id: 1, // Always a number (user always sends it)
        extraNode: <ExampleComponent />, // If it's sent, it's React component (user may not send it)

        // From here, we can receive anything because it depends on what
        // the database sends. The type is always a string, but I can have
        // many other values such as height, age, etc...
        position: '1',
        player: 'Miroslav Klose',
        goals: '16',
        games: '24',
        country: 'Germany',
    },
    {
        id: 2,
        extraNode: <ExampleComponent />,
        position: '2',
        player: 'Ronaldo',
        goals: '15',
        games: '19',
        country: 'Brazil',
    },
];

id 将始终是一个数字,extraNode 将是一个 React 组件(如果它通过了)。问题是其他键值是动态的。这意味着它可以更多,例如年龄,身高等。

我试过这个,但它给了我一个错误:

export interface tableData {
    id: number;
    extraNode?: React.ReactNode;
    [key: string]: string;
  }
  
export interface TableProps extends HTMLAttributes<HTMLDivElement> {
    tableData: tableData[];
}

标签: typescriptreact-typescript

解决方案


你可以使用一个Record

type Player = Record<string, string>

interface Data {
    id: number;
    extraNode: React.ReactNode;
    player: Player;
}

const test:Data = {
    id: 123,
    extraNode: <Component />
    player:{
        position: "1",
        player: "Miroslav Klose"
    }
}

推荐阅读