我已经定义了类型,但我仍然收到一个错误:
绑定元素"title"隐式具有"any"类型。
这一行上的id、标题和正文
static getInitialProps({ query: { id, title, body } }) {
这是我的代码:从"React"导入React,{Component};
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>
)
}
}
由于getInitialProps
不是Component
的一部分,因此没有任何东西告诉TypeScript它将接收或返回什么,因此您必须这样做。
看起来您希望查询字符串包含id
、title
和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
道具,但在Props
类型中也没有将其列为可选。
注意,以上所有内容都为Next.js将传递到getInitialProps
的上下文参数提供了一个类型,但它们没有为getInitialProps
的返回值提供类型。为了完整性,您可能还需要提供。由于您返回的只是Props
的一部分,所以类型应该是Partial<Props>
。
例如,使用QueryParams
(上面的中间选项,这是我最喜欢的选项(:
type QueryParams = {
id: string;
title: string;
body: string;
};
然后
static getInitialProps({ query: { id, title, body } }: { query: QueryParams }): Partial<Props> {
// Type of the parameter −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^−−−− type of the return value
return { postId: id, title, body };
}
以上内容包含在您的代码中:
type Props = {
id: number;
title: string;
body: string;
postId: string;
};
type QueryParams = {
id: string;
title: string;
body: string;
};
export default class extends Component <Props> {
static getInitialProps({ query: { id, title, body } }: { query: QueryParams }): Partial<Props> {
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>
);
}
}