首页 > 解决方案 > 传递给组件时打字稿混乱

问题描述

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

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

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

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

例如,

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

然后,在从以下位置接收所有数据的 Layout 组件中Home

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

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

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

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

您如何防止必须一直声明和重复类型?

标签: javascripttypescript

解决方案


有点不清楚您在做什么,因为我没有看到示例和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基于偏好或编码标准。

打字稿游乐场


推荐阅读