绑定元素'title'隐式具有'any'类型

问题描述 投票:1回答:1

我已经定义了类型,但是仍然出现错误说明:

绑定元素'title'隐式具有'any'类型。

此行上的ID,标题和正文

static getInitialProps({ query: { id, title, body } }) {

这是我的代码:从'react'导入React,{组件};

type Props={
    id: number;
    title: string;
    body: string;
    postId: string;
}

export default class extends Component <Props> {
  static getInitialProps({ query: { id, title, body } }) {
    return { postId: id, title, body }
  }

  render() {
    return (
      <div>
        <h1>My blog post #{this.props.postId}</h1>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliqua.
        </p>
      </div>
    )
  }
}
reactjs typescript types next.js
1个回答
0
投票

由于getInitialProps不是getInitialProps的一部分,所以没有任何内容告诉TypeScript它将接收或返回什么,所以您必须这样做。

似乎您期望查询字符串包含Componentidtitle(所有字符串)。由于这不是您的body类型,因此可以定义该内联:

Props

...或者因为内联类型有点笨拙:

static getInitialProps({ query: { id, title, body } }: { query: {id: string, title: string, body: string} }) {
    return { postId: id, title, body };
}

然后

type QueryParams = {
    id: string;
    title: string;
    body: string;
};

甚至

static getInitialProps({ query: { id, title, body } }: { query: QueryParams }) {
    return { postId: id, title, body };
}

然后

type PartialContext = {
    query: {
        id: string;
        title: string;
        body: string;
    };
};

我说过,您的static getInitialProps({ query: { id, title, body } }: PartialContext) { return { postId: id, title, body }; } 不提供getInitialProps道具,但在id类型中也未列为可选。


[注意,以上所有内容都为Next.js将传递给Props的上下文参数提供了一种类型,但它们没有为getInitialProps的返回值提供一种类型。为了完整起见,您可能还希望提供它。由于返回的内容只是getInitialProps的一部分,因此类型为Props

例如,使用Partial<Props>(上面的中间选项,这是我最喜欢的选项):

QueryParams

然后

type QueryParams = {
    id: string;
    title: string;
    body: string;
};
© www.soinside.com 2019 - 2024. All rights reserved.