首页 > 解决方案 > 打字稿声明合并原因是指一个值,但在反应中被用作类型

问题描述

我试图找到一种方法来避免绞尽脑汁想出一个名称,而不会因为 diff 声明和组件名称的后缀或前缀而破坏优雅。

我受到此链接的启发,避免在 TypeScript 中的对象和接口之间重复标识符 以使用声明合并。但似乎一切都在合并后一团糟。它既不检测类型也不检测值。

示例文件:


//Player.tsx
interface Player {
  id: number
  name: string
  status: string
  avatar: string
}

const Player: React.FC<Player> = ({name, status, avatar}) => (
  <div className="flex">
    <span className="block w-20 h-20 rounded-full bg-green-200">{avatar}</span>
    <span className="pl-5 flex flex-col justify-center">
      <p className="text-lg">{name}</p>
      <p>{status}</p>
    </span>
  </div>
)

export default Player

这样,我得到了错误:

//ListPlayer.tsx
import Player from './Player';

export interface Props {
  items: Player[]  //'Player' refers to a value, but is being used as a type here. Did you mean 'typeof Player'?
}
const ListPlayer: React.FC<Props> = ({ items }) => (
  <>
    {items.map((item) => (
      <Player {...item} />
    ))}
  </>
);
export default ListPlayer;

如果我使用 typeof,上面的错误将被修复,但是,得到另一个错误:

//ListPlayer.tsx
import Player from './Player';

export interface Props {
   items: typeof Player[]
}
const ListPlayer: React.FC<Props> = ({ items }) => (
  <>
    {items.map((item) => (
      <Player {...item} /> //Type '{ propTypes?: WeakValidationMap<Player> | undefined; contextTypes?: ValidationMap<any> | undefined; defaultProps?: Partial<Player> | undefined; displayName?: string | undefined; }' is missing the following properties from type 'Player': id, name, status, avatarts(2739)
    ))}
  </>
);
export default ListPlayer;

我想知道我的代码有什么问题?

标签: reactjstypescript

解决方案


您将项目道具与 Player 组件混淆。

定义 PlayerProps 接口并导出:

import React from 'react'
export interface PlayerProps {
  id: number
  name: string
  status: string
  avatar: string
}

const Player: React.FC<PlayerProps> = ({name, status, avatar}) => (
  <div className="flex">
    <span className="block w-20 h-20 rounded-full bg-green-200">{avatar}</span>
    <span className="pl-5 flex flex-col justify-center">
      <p className="text-lg">{name}</p>
      <p>{status}</p>
    </span>
  </div>
)

export default Player

对于 ListPlayer,您应该使用接口 PlayerPros 定义道具,如下所示:

import React from 'react'
import Player, {PlayerProps} from './Player';

export interface Props {
  items: PlayerProps[]
}
const ListPlayer: React.FC<Props> = ({ items }) => (
  <>
    {items.map((item) => (
      <Player {...item} />
    ))}
  </>
);
export default ListPlayer;

推荐阅读