传递给组件时打字稿混乱

时间:2021-06-23 18:35:23

标签: javascript typescript

我对 Typescript 很陌生,但想更好地了解它的来龙去脉。

假设我查询或获取一些以这种形式返回的数据

{
  data: {
    edges: {
      node: {
        id: '123',
        label: 'test',
        seo: {...}
        etc...
      }
    }
  }
}

当我将其传递给页面、组件等时(使用 Nextjs),由于解构和其他道具,我似乎必须为每个组件稍微添加这些类型。

例如

const Home = (props: QueryResult) => ... // QueryResult taking the shape of the above object

然后,在从 Home 接收所有数据的 Layout 组件中:

const Layout = ({ children, data, isPost }: DefaultProps)

另一轮声明,这次包括 children 和 isPost。我编写了另一个接口,在其中引用了 Home 文件中的 QueryResult。

现在,Layout 有一个 SEO 组件,它接收 data.edges.node.seo,还有另一个类型声明来描述所有的 Seo 类型等。我希望我的目标变得清晰。

我错过了什么吗?有没有更简洁的方法来做到这一点,例如编写一个更大的界面,然后在需要的地方借用某些类型?

您如何防止一直声明和复制类型?

1 个答案:

答案 0 :(得分:0)

您在做什么有点不清楚,因为我没有看到示例和您提到的 Home 的 1:1。

如果您为需要作为参数或返回值接受的所有数据声明类型或接口,请自下而上构建“顶层”,而您的子组件仅使用您已声明的较小类型。没有重复。

type seoType = { /* stuff */ };
type nodeType = {
  id: string;
  label: string;
  seo: seoType;
};
type dataType = {
  edges: {
    node: nodeType;
  }
};
type topLevelType = {
  data: dataType;
}

const topLevel: topLevelType = {
  data: {
    edges: {
      node: {
        id: '123',
        label: 'test',
        seo: { /* stuff */ }
      }
    }
  }
}

您可以根据偏好或编码标准使用 interface 代替 type

TypeScript Playground