React 属性 XXX 在类型 'YYY' 中缺失,但在类型 'ZZZ' 中是必需的

React property XXX is missing in type 'YYY' but required in type 'ZZZ'

import { Link } from "react-router-dom";
export interface AvatarSize {
  avatarSize: number;
}

export interface PageInterface extends AvatarSize {
  user: {
    permaLink: string;
  };
}

const data = {
  user: {
    permaLink:
      "https://images.unsplash.com/photo-1590698933947-a202b069a861?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTF8fGhhcHB5fGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
  },
  avatarSize: 50
};

const App = () => <Page user={data} />; // user is 

const Page = (props: PageInterface) => (
  <PageLayout user={props.user} avatarSize={props.avatarSize} />
);

const PageLayout = (props: PageInterface) => (
  <NavigationBar user={props.user} avatarSize={props.avatarSize} />
);

const NavigationBar = (props: PageInterface) => (
  <Link to={props.user.permaLink}>
    <Avatar avatarSize={props.avatarSize} />
  </Link>
);

const Avatar = (props: AvatarSize) => (
  <div>Avatar Size: {props.avatarSize}</div>
)

export default App;

我刚开始学习 React,上面的源码报错,但我不知道如何解决这个问题。我认为这可能与打字稿界面没有反应有关。

其实你定义的是data的界面,而不是页面属性。您可以做两件事来修复它,要么更改道具的类型,要么将 useravatarSize 直接发送到道具中。

方法一:

const Page = (props: { user: PageInterface }) => (
  <PageLayout user={props.user.user} avatarSize={props.user.avatarSize} />
);

方法二:(推荐)

const App = () => <Page user={data.user} avatarSize={data.avatarSize} />;