传递到组件时打字混乱



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

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

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

当我把它传递到页面、组件等时(使用Nextjs(,由于析构函数和其他道具,我似乎不得不为每个组件稍微添加这些类型。

例如,

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

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

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

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

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

我是不是错过了什么?有没有更干净的方法可以做到这一点,例如写一次更大的接口,然后在需要的地方从中借用某些类型?

如何避免一直声明和重复类型?

您正在做什么有点不清楚,因为我没有看到您提到的示例和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游乐场

最新更新