【问题标题】:How to define the type for use the spread operator to pass props如何定义使用扩展运算符传递道具的类型
【发布时间】:2021-06-15 10:40:19
【问题描述】:
type TypeData = {
  data: {
    id: string;
    class: string;
    name: string;
    country: string;
    ew_get_url: string;
    ew_post_url: string;
    rocket_id: string;
    pages: {
      landing: {
        h1: string;
        h2: string;
      }
    }
  }
}

我不能使用扩展运算符,错误在元素中,VSC显示错误

类型 '{ id: string; 中缺少属性 'data'类:字符串;名称:字符串;国家:字符串; ew_get_url:字符串; ew_post_url:字符串;火箭ID:字符串;页面:{登陆:{h1:字符串; h2:字符串; }; }; }' 但在“PropsType”类型中是必需的。

export default function Funnel(props: TypeData): JSX.Element {
  const { data } = props;

  return (
    <>
      <Head><title>Start your own e-Comm biz now!</title></Head>

      <DataTest data={data} />
      <div style={{
        backgroundImage: `url("/img/${data.class}/landing/bg.jpg")`,
        backgroundAttachment: 'fixed',
        backgroundSize: 'cover',
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'center center',
        minHeight: '100vh'
      }}>
        **<Template {...data}></Template>**
      </div>
    </>
  );
}

【问题讨论】:

  • Template props 的类型是什么?

标签: reactjs typescript typescript-typings


【解决方案1】:

在 PropsType 中,您要求提供“数据”属性(可能您指定了 TypeData)。 但是,您传递数据对象内部的属性(因为扩展运算符解包对象)。 所以模板需要: { data: {id: string;类:字符串;名称:字符串 ...} } 您提供:{ id: string;类:字符串;名称:字符串... }

您可以删除扩展运算符,只为模板传入数据。 或者你修改模板的 PropsType。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2014-10-27
    相关资源
    最近更新 更多