简体   繁体   English

Typescript 接口不接受带有强制键的动态对象

[英]Typescript interface doesn't accept dynamic object with mandatory keys

I need to use an interface for this array of objects that it's passed as prop.我需要为这个作为道具传递的对象数组使用一个接口。

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 will always be a number, extraNode will be a React Component (if it's passed). id 将始终是一个数字, extraNode 将是一个 React 组件(如果它通过)。 The problem is that the other key-values are dynamic.问题在于其他键值是动态的。 It means that it can be more such as age, height, etc.这意味着它可以更多,例如年龄,身高等。

I tried this, but it's giving me an error:我试过这个,但它给了我一个错误:

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

you can use a Record你可以使用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"
    }
}

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

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