【问题标题】:Typescript object literal may only specify known properties error打字稿对象文字可能只指定已知属性错误
【发布时间】:2019-10-07 16:00:18
【问题描述】:

我是打字稿/反应的新手。我有这种类型的错误,我不确定如何解决。有人可以启发我吗?

错误: [tsc] src/webparts/jsonFeed/components/JsonFeed.tsx(40,8): error TS2322: Type '{ postOrLinkedIn: any; }' 不可分配给类型 'ReactElement ReactElement ReactElement

JsonFeed.tsx

export default class JsonFeed extends React.Component<IJsonFeedProps, IJsonFeedState> {

  // State needed for the component
  constructor(props) {
    super(props);
    this.state = {
      description: this.props.description,
      posts: [],
      profile: {},
      isLoading: true,
      jsonUrl: this.props.jsonUrl, // This was just for testing purposes
      postCount: this.props.postCount,
      errors: null,
      error: null,
      listName: this.props.listName, // This will actually select the list
      item: this.props.item, // This will actually select the list
    };
  }

  // Renders to the browser
  public render(): React.ReactElement<IJsonFeedProps> {

    let postOrLinkedIn;
    if (this.props.item !== 'linkedin') {
      postOrLinkedIn = <Posts />;
    } else {
      postOrLinkedIn = <Linkedin />;
    }  

    // What we render
    return (
      {postOrLinkedIn}
    );
  }

}

IJsonFeedProps:

export interface IJsonFeedProps {
  description?: string;
  postCount?: number;
  jsonUrl?: string;
  listName?: string;
  item?: string;
  posts?: any;
  postOrLinkedIn?: boolean;
}

【问题讨论】:

  • 完全错误:错误 - [tsc] src/webparts/jsonFeed/components/JsonFeed.tsx(40,8): error TS2322: Type '{ postOrLinkedIn: any; }' 不可分配给类型 'ReactElement ReactElement ReactElement
  • 接口中的 postOrLinkedIn 被声明为布尔值,当您在组件中使用该属性时,您正在为其分配一个 ReactElement。尝试将接口更新为postOrLinkedIn?: React.ReactElement&lt;any&gt;。 TypeScript 通过抛出错误来完成其工作,因为它不是布尔值。

标签: reactjs typescript


【解决方案1】:

您在IJsonFeedProps 中指定postOrLinkedIn 要么是未定义的要么是布尔值。而在渲染函数中,您返回的是 JSX.Element。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 2019-05-14
    • 2018-09-06
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    相关资源
    最近更新 更多