我正在尝试创建一个可重复使用的React组件:一个表,该表应该是“团队”列表或“游戏”列表。因此,GraphQL查询根据所获取的内容而有所不同。
所以我有那些接口和类型:
export interface Team {
id: string;
name: string;
}
export interface Game {
id: string;
competition: string;
}
export interface Data {
allElems?: Team[] | Game[]
[elements: string]: Team[] | Game[] | undefined
}
我的组件是这样的:
interface SectionTableProps {
query: object
}
class SectionTableQuery extends Query<Data, {}> {}
class SectionTable extends React.Component<SectionTableProps, {}> {
constructor(props: SectionTableProps) {
super(props);
}
render() {
return (
<SectionTableQuery query={this.props.query}>
{({ data = {}, error, loading }) => {
if (loading) {
return <tbody><tr><td>LOADING</td></tr></tbody>
};
if (error !== undefined) {
return <tbody><tr><td>ERROR</td></tr></tbody>
};
return (
<tbody>
{Object.keys(data).map(elements => {
data[elements].map(
elem => (
<tr key={elem.id} >
<th scope="row">{elem.id}</th>
{Object.keys(elem).map(k => {
if (k !== "id" && k !== "__typename") {
return <td key={elem[k]}>{elem[k]}</td>
}
})}
</tr>
)
)
}
)
}
</tbody>
);
}}
</SectionTableQuery>
)
}
}
但是出现以下错误:
TypeScript error: Cannot invoke an expression whose type lacks a call signature. Type '(<U>(callbackfn: (value: Team, index: number, array: Team[]) => U, thisArg?: any) => U[]) | (<U>(callbackfn: (value: Game, index: number, array: Game[]) => U, thisArg?: any) => U[])' has no compatible call signatures. TS2349
42 | <tbody>
43 | {Object.keys(data).map(elements => {
> 44 | (data[elements] || []).map(
| ^
45 | elem => (
46 | <tr key={elem.id}>
47 | <th scope="row">{elem.id}</th>
为什么会这样?我真的不知道为什么Game
和Team
不兼容...
答案 0 :(得分:1)
只是找到了解决方案;不知道这是否是最好的:
就我而言,我必须使用declaration merging:
我不会写
export interface Team {
id: string;
name: string;
}
export interface Game {
id: string;
competition: string;
}
export interface Data {
allElems?: Team[] | Game[]
[elements: string]: Team[] | Game[] | undefined
}
因为我会在第一篇文章中提到错误。相反,我必须这样声明我的接口:
//team
interface Elem {
id: string;
name?: string;
[attr: string]: string | number | undefined
}
//game
interface Elem {
id: string;
homeTeamScore?: number
competition?: string
round?: string
}
export interface Data {
elem?: Elem
[elements: string]: Elem | undefined
}
在最基本的级别上,合并会机械地连接的成员 这两个声明都放入同一个名称的单个接口中。